@nordsym/apiclaw 2.0.0 → 2.2.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.
@@ -3,7 +3,11 @@
3
3
  "allow": [
4
4
  "Bash(CONVEX_DEPLOYMENT=\"prod:adventurous-avocet-799\" npx convex env set STRIPE_PRICE_ID_USAGE \"price_1TL038RtJYK3aJTqODoFAiVT\")",
5
5
  "Bash(npx convex:*)",
6
- "Bash(CONVEX_DEPLOYMENT=\"prod:adventurous-avocet-799\" npx convex deploy -y)"
6
+ "Bash(CONVEX_DEPLOYMENT=\"prod:adventurous-avocet-799\" npx convex deploy -y)",
7
+ "Bash(git add:*)",
8
+ "Bash(git commit -m ':*)",
9
+ "Bash(git push:*)",
10
+ "Bash(npx vercel:*)"
7
11
  ]
8
12
  }
9
13
  }
@@ -8,6 +8,7 @@
8
8
  * @module
9
9
  */
10
10
 
11
+ import type * as _listWorkspaces from "../_listWorkspaces.js";
11
12
  import type * as adminActivate from "../adminActivate.js";
12
13
  import type * as adminStats from "../adminStats.js";
13
14
  import type * as agents from "../agents.js";
@@ -26,6 +27,8 @@ import type * as directCall from "../directCall.js";
26
27
  import type * as earnProgress from "../earnProgress.js";
27
28
  import type * as email from "../email.js";
28
29
  import type * as feedback from "../feedback.js";
30
+ import type * as funnel from "../funnel.js";
31
+ import type * as guards from "../guards.js";
29
32
  import type * as http from "../http.js";
30
33
  import type * as inbound from "../inbound.js";
31
34
  import type * as logs from "../logs.js";
@@ -34,6 +37,7 @@ import type * as migratePartnersProd from "../migratePartnersProd.js";
34
37
  import type * as migratePratham from "../migratePratham.js";
35
38
  import type * as migrateProviderWorkspaces from "../migrateProviderWorkspaces.js";
36
39
  import type * as mou from "../mou.js";
40
+ import type * as nurture from "../nurture.js";
37
41
  import type * as providerKeys from "../providerKeys.js";
38
42
  import type * as providers from "../providers.js";
39
43
  import type * as purchases from "../purchases.js";
@@ -61,6 +65,7 @@ import type {
61
65
  } from "convex/server";
62
66
 
63
67
  declare const fullApi: ApiFromModules<{
68
+ _listWorkspaces: typeof _listWorkspaces;
64
69
  adminActivate: typeof adminActivate;
65
70
  adminStats: typeof adminStats;
66
71
  agents: typeof agents;
@@ -79,6 +84,8 @@ declare const fullApi: ApiFromModules<{
79
84
  earnProgress: typeof earnProgress;
80
85
  email: typeof email;
81
86
  feedback: typeof feedback;
87
+ funnel: typeof funnel;
88
+ guards: typeof guards;
82
89
  http: typeof http;
83
90
  inbound: typeof inbound;
84
91
  logs: typeof logs;
@@ -87,6 +94,7 @@ declare const fullApi: ApiFromModules<{
87
94
  migratePratham: typeof migratePratham;
88
95
  migrateProviderWorkspaces: typeof migrateProviderWorkspaces;
89
96
  mou: typeof mou;
97
+ nurture: typeof nurture;
90
98
  providerKeys: typeof providerKeys;
91
99
  providers: typeof providers;
92
100
  purchases: typeof purchases;
@@ -0,0 +1,13 @@
1
+ import { query } from "./_generated/server";
2
+ export const run = query({
3
+ args: {},
4
+ handler: async (ctx) => {
5
+ const ws = await ctx.db.query("workspaces").collect();
6
+ return ws.map((w) => ({
7
+ id: w._id,
8
+ email: (w as any).email || (w as any).ownerEmail || null,
9
+ name: (w as any).name || (w as any).workspaceName || null,
10
+ createdAt: w._creationTime,
11
+ }));
12
+ },
13
+ });
package/convex/crons.ts CHANGED
@@ -47,4 +47,19 @@ crons.monthly(
47
47
  internal.usageReports.sendMonthlyReports
48
48
  );
49
49
 
50
+ // Nurture classifier — daily at 06:00 UTC, upserts each workspace's lifecycle stage
51
+ crons.daily(
52
+ "nurture-classify",
53
+ { hourUTC: 6, minuteUTC: 0 },
54
+ internal.nurture.classifyAllWorkspaces
55
+ );
56
+
57
+ // Nurture sender — daily at 09:30 UTC (11:30 CEST), caps at 12 emails/day
58
+ crons.daily(
59
+ "nurture-send",
60
+ { hourUTC: 9, minuteUTC: 30 },
61
+ internal.nurture.sendDailyNurture,
62
+ { maxSends: 12 }
63
+ );
64
+
50
65
  export default crons;
@@ -0,0 +1,431 @@
1
+ /**
2
+ * APIClaw Funnel — canonical conversion truth
3
+ *
4
+ * Canon events (ordered):
5
+ * install — package installed (postinstall hook, once per fingerprint)
6
+ * first_run — MCP server first successful startup
7
+ * register_owner — user called register_owner (OTP sent)
8
+ * verify_code — user verified OTP, workspace active
9
+ * first_call_api_success — workspace's first successful call_api (non-discover)
10
+ *
11
+ * Classification (source):
12
+ * human — real user, reasonable UA, interactive MCP client
13
+ * ci — CI/CD runner (CI env var family, GITHUB_ACTIONS, headless UAs)
14
+ * bot — scanner/crawler (User-Agent matches crawler list)
15
+ * internal — NordSym test traffic (fingerprint prefix, allowlisted emails)
16
+ *
17
+ * Truth metrics are built from (event=verify_code AND source=human) and
18
+ * (event=first_call_api_success AND source=human). Vanity = install count.
19
+ */
20
+ import { mutation, query, internalMutation } from "./_generated/server";
21
+ import { v } from "convex/values";
22
+
23
+ export const FUNNEL_EVENTS = [
24
+ "install",
25
+ "first_run",
26
+ "register_owner",
27
+ "verify_code",
28
+ "first_call_api_success",
29
+ ] as const;
30
+
31
+ export type FunnelEvent = (typeof FUNNEL_EVENTS)[number];
32
+
33
+ // Diagnostic events — reasoning, errors, retries, drop-off causes.
34
+ // Stored in the same table but excluded from the canonical funnel rollup.
35
+ export const DIAGNOSTIC_EVENTS = [
36
+ "register_owner_failed", // props: { reason: "invalid_email" | "email_send_failed" }
37
+ "verify_code_failed", // props: { reason: "invalid" | "expired" | "attempts_exceeded" }
38
+ "call_api_blocked", // props: { reason: "no_session" | "pending_verification" | "quota_exceeded" | "not_verified" }
39
+ "call_api_error", // props: { provider, action, errorCode }
40
+ "quota_hit", // props: { tier, limit }
41
+ "gateway_retry", // props: { attempt, reason }
42
+ ] as const;
43
+
44
+ export type DiagnosticEvent = (typeof DIAGNOSTIC_EVENTS)[number];
45
+ export type AnyEvent = FunnelEvent | DiagnosticEvent;
46
+
47
+ const ALL_EVENTS = [...FUNNEL_EVENTS, ...DIAGNOSTIC_EVENTS] as readonly string[];
48
+
49
+ export type Classification = "human" | "ci" | "bot" | "internal";
50
+
51
+ // Keep these predicates pure and exported so tests can hit them directly.
52
+ const CI_ENV_KEYS = [
53
+ "CI",
54
+ "GITHUB_ACTIONS",
55
+ "GITLAB_CI",
56
+ "CIRCLECI",
57
+ "BUILDKITE",
58
+ "JENKINS_URL",
59
+ "TEAMCITY_VERSION",
60
+ "TRAVIS",
61
+ "BITBUCKET_BUILD_NUMBER",
62
+ ];
63
+
64
+ // UA substrings (lower-cased) that flag known bots/scanners.
65
+ const BOT_UA_MARKERS = [
66
+ "bot",
67
+ "crawl",
68
+ "spider",
69
+ "scanner",
70
+ "curl/",
71
+ "wget/",
72
+ "httpclient",
73
+ "python-requests",
74
+ "go-http-client",
75
+ "okhttp",
76
+ "java/",
77
+ "httrack",
78
+ "headlesschrome",
79
+ "phantomjs",
80
+ ];
81
+
82
+ // Emails that are considered internal NordSym traffic.
83
+ const INTERNAL_EMAIL_DOMAINS = ["nordsym.com", "apiclaw.cloud"];
84
+ const INTERNAL_EMAIL_EXACT = ["gustav@nordsym.com", "gustavnordsync@gmail.com"];
85
+
86
+ // Fingerprint prefix(es) used by internal test machines.
87
+ const INTERNAL_FINGERPRINT_PREFIXES: string[] = [];
88
+
89
+ export function classifySource(input: {
90
+ userAgent?: string | null;
91
+ envFlags?: Record<string, string | undefined>;
92
+ email?: string | null;
93
+ fingerprint?: string | null;
94
+ forcedInternal?: boolean;
95
+ }): Classification {
96
+ if (input.forcedInternal) return "internal";
97
+
98
+ const email = (input.email || "").toLowerCase().trim();
99
+ if (email) {
100
+ if (INTERNAL_EMAIL_EXACT.includes(email)) return "internal";
101
+ const domain = email.split("@")[1] || "";
102
+ if (INTERNAL_EMAIL_DOMAINS.includes(domain)) return "internal";
103
+ }
104
+
105
+ const fp = input.fingerprint || "";
106
+ if (fp && INTERNAL_FINGERPRINT_PREFIXES.some((p) => fp.startsWith(p))) {
107
+ return "internal";
108
+ }
109
+
110
+ const env = input.envFlags || {};
111
+ for (const key of CI_ENV_KEYS) {
112
+ const val = env[key];
113
+ if (val && val !== "false" && val !== "0") return "ci";
114
+ }
115
+
116
+ const ua = (input.userAgent || "").toLowerCase();
117
+ if (ua) {
118
+ for (const m of BOT_UA_MARKERS) {
119
+ if (ua.includes(m)) return "bot";
120
+ }
121
+ }
122
+
123
+ return "human";
124
+ }
125
+
126
+ // Record a funnel event. Idempotent per (workspaceId|fingerprint, event) for
127
+ // first-time events (install, first_run, first_call_api_success) via
128
+ // dedupeKey. register_owner and verify_code can recur legitimately.
129
+ export const recordEvent = mutation({
130
+ args: {
131
+ event: v.string(), // validated against FUNNEL_EVENTS below
132
+ classification: v.string(),
133
+ workspaceId: v.optional(v.id("workspaces")),
134
+ fingerprint: v.optional(v.string()),
135
+ sessionToken: v.optional(v.string()),
136
+ email: v.optional(v.string()),
137
+ userAgent: v.optional(v.string()),
138
+ mcpClient: v.optional(v.string()),
139
+ platform: v.optional(v.string()),
140
+ version: v.optional(v.string()),
141
+ dedupeKey: v.optional(v.string()), // if set, no-op when duplicate exists
142
+ props: v.optional(v.any()),
143
+ },
144
+ handler: async (ctx, args) => {
145
+ if (!ALL_EVENTS.includes(args.event)) {
146
+ return { success: false, error: `unknown_event:${args.event}` };
147
+ }
148
+ const allowedClass: Classification[] = ["human", "ci", "bot", "internal"];
149
+ if (!allowedClass.includes(args.classification as Classification)) {
150
+ return { success: false, error: `unknown_classification:${args.classification}` };
151
+ }
152
+
153
+ if (args.dedupeKey) {
154
+ const existing = await ctx.db
155
+ .query("funnelEvents")
156
+ .withIndex("by_dedupeKey", (q) => q.eq("dedupeKey", args.dedupeKey!))
157
+ .first();
158
+ if (existing) {
159
+ return { success: true, deduped: true, id: existing._id };
160
+ }
161
+ }
162
+
163
+ const id = await ctx.db.insert("funnelEvents", {
164
+ event: args.event,
165
+ classification: args.classification,
166
+ workspaceId: args.workspaceId,
167
+ fingerprint: args.fingerprint,
168
+ sessionToken: args.sessionToken,
169
+ email: args.email,
170
+ userAgent: args.userAgent,
171
+ mcpClient: args.mcpClient,
172
+ platform: args.platform,
173
+ version: args.version,
174
+ dedupeKey: args.dedupeKey,
175
+ props: args.props,
176
+ timestamp: Date.now(),
177
+ });
178
+
179
+ return { success: true, deduped: false, id };
180
+ },
181
+ });
182
+
183
+ // Internal variant callable from other Convex functions (e.g. verifyOTP).
184
+ export const recordEventInternal = internalMutation({
185
+ args: {
186
+ event: v.string(),
187
+ classification: v.string(),
188
+ workspaceId: v.optional(v.id("workspaces")),
189
+ fingerprint: v.optional(v.string()),
190
+ email: v.optional(v.string()),
191
+ dedupeKey: v.optional(v.string()),
192
+ props: v.optional(v.any()),
193
+ },
194
+ handler: async (ctx, args) => {
195
+ if (!ALL_EVENTS.includes(args.event)) return null;
196
+ if (args.dedupeKey) {
197
+ const existing = await ctx.db
198
+ .query("funnelEvents")
199
+ .withIndex("by_dedupeKey", (q) => q.eq("dedupeKey", args.dedupeKey!))
200
+ .first();
201
+ if (existing) return existing._id;
202
+ }
203
+ return await ctx.db.insert("funnelEvents", {
204
+ ...args,
205
+ timestamp: Date.now(),
206
+ });
207
+ },
208
+ });
209
+
210
+ // Roll up the canonical funnel for a time window. Default: last 7d, human only.
211
+ export const getFunnel = query({
212
+ args: {
213
+ hoursBack: v.optional(v.number()),
214
+ includeClassifications: v.optional(v.array(v.string())),
215
+ },
216
+ handler: async (ctx, args) => {
217
+ const hoursBack = args.hoursBack ?? 24 * 7;
218
+ const since = Date.now() - hoursBack * 3600000;
219
+ const includes = args.includeClassifications ?? ["human"];
220
+
221
+ const events = await ctx.db
222
+ .query("funnelEvents")
223
+ .withIndex("by_timestamp", (q) => q.gte("timestamp", since))
224
+ .collect();
225
+
226
+ const filtered = events.filter((e) => includes.includes(e.classification));
227
+
228
+ const countsByEvent: Record<string, number> = {};
229
+ const uniqByEvent: Record<string, Set<string>> = {};
230
+ for (const e of FUNNEL_EVENTS) {
231
+ countsByEvent[e] = 0;
232
+ uniqByEvent[e] = new Set<string>();
233
+ }
234
+
235
+ for (const e of filtered) {
236
+ countsByEvent[e.event] = (countsByEvent[e.event] || 0) + 1;
237
+ const k = (e.workspaceId as string | undefined) || e.fingerprint || e._id;
238
+ uniqByEvent[e.event].add(k);
239
+ }
240
+
241
+ // Classification breakdown across all events in window.
242
+ const byClass: Record<string, number> = { human: 0, ci: 0, bot: 0, internal: 0 };
243
+ for (const e of events) {
244
+ byClass[e.classification] = (byClass[e.classification] || 0) + 1;
245
+ }
246
+
247
+ const funnel = FUNNEL_EVENTS.map((name) => ({
248
+ event: name,
249
+ count: countsByEvent[name],
250
+ unique: uniqByEvent[name].size,
251
+ }));
252
+
253
+ // Conversion ratios (unique-based).
254
+ const get = (n: string) => uniqByEvent[n]?.size || 0;
255
+ const ratios = {
256
+ install_to_first_run: safeRatio(get("first_run"), get("install")),
257
+ first_run_to_register: safeRatio(get("register_owner"), get("first_run")),
258
+ register_to_verify: safeRatio(get("verify_code"), get("register_owner")),
259
+ verify_to_first_call: safeRatio(get("first_call_api_success"), get("verify_code")),
260
+ install_to_verify: safeRatio(get("verify_code"), get("install")),
261
+ install_to_first_call: safeRatio(get("first_call_api_success"), get("install")),
262
+ };
263
+
264
+ return {
265
+ windowHours: hoursBack,
266
+ includeClassifications: includes,
267
+ totalEvents: filtered.length,
268
+ funnel,
269
+ ratios,
270
+ classificationBreakdown: byClass,
271
+ };
272
+ },
273
+ });
274
+
275
+ function safeRatio(num: number, denom: number): number {
276
+ if (!denom) return 0;
277
+ return Math.round((num / denom) * 10000) / 10000;
278
+ }
279
+
280
+ // Weekly scorecard — the canonical KPI snapshot.
281
+ // Returns truth metrics (human-only by default) with optional comparison
282
+ // against the previous period of equal length.
283
+ export const getScorecard = query({
284
+ args: {
285
+ hoursBack: v.optional(v.number()),
286
+ classification: v.optional(v.string()), // "human" by default
287
+ compare: v.optional(v.boolean()), // compare to prior equal window
288
+ },
289
+ handler: async (ctx, args) => {
290
+ const windowH = args.hoursBack ?? 24 * 7;
291
+ const cls = args.classification ?? "human";
292
+ const now = Date.now();
293
+ const since = now - windowH * 3600000;
294
+ const priorSince = now - windowH * 2 * 3600000;
295
+
296
+ const events = await ctx.db
297
+ .query("funnelEvents")
298
+ .withIndex("by_timestamp", (q) => q.gte("timestamp", args.compare ? priorSince : since))
299
+ .collect();
300
+
301
+ const window = events.filter((e) => e.timestamp >= since && e.classification === cls);
302
+ const prior = args.compare
303
+ ? events.filter(
304
+ (e) =>
305
+ e.timestamp >= priorSince &&
306
+ e.timestamp < since &&
307
+ e.classification === cls
308
+ )
309
+ : null;
310
+
311
+ const metrics = computeMetrics(window);
312
+ const priorMetrics = prior ? computeMetrics(prior) : null;
313
+
314
+ // Diagnostic breakdown for the current window.
315
+ const diagnostics: Record<string, Record<string, number>> = {};
316
+ for (const e of window) {
317
+ if (!DIAGNOSTIC_EVENTS.includes(e.event as DiagnosticEvent)) continue;
318
+ const reason = ((e.props as any)?.reason ?? "unknown") as string;
319
+ diagnostics[e.event] = diagnostics[e.event] || {};
320
+ diagnostics[e.event][reason] = (diagnostics[e.event][reason] || 0) + 1;
321
+ }
322
+
323
+ return {
324
+ windowHours: windowH,
325
+ classification: cls,
326
+ generatedAt: now,
327
+ truth: {
328
+ installs: metrics.unique.install,
329
+ activatedOwners: metrics.unique.verify_code,
330
+ activatedUsers: metrics.unique.first_call_api_success,
331
+ },
332
+ vanity: {
333
+ installEvents: metrics.counts.install,
334
+ },
335
+ ratios: metrics.ratios,
336
+ diagnostics,
337
+ previous: priorMetrics
338
+ ? {
339
+ installs: priorMetrics.unique.install,
340
+ activatedOwners: priorMetrics.unique.verify_code,
341
+ activatedUsers: priorMetrics.unique.first_call_api_success,
342
+ ratios: priorMetrics.ratios,
343
+ }
344
+ : null,
345
+ };
346
+ },
347
+ });
348
+
349
+ type FunnelBucket = {
350
+ counts: Record<string, number>;
351
+ unique: Record<string, number>;
352
+ ratios: Record<string, number>;
353
+ };
354
+
355
+ function computeMetrics(events: { event: string; workspaceId?: any; fingerprint?: any; _id: any }[]): FunnelBucket {
356
+ const counts: Record<string, number> = {};
357
+ const uniq: Record<string, Set<string>> = {};
358
+ for (const e of FUNNEL_EVENTS) {
359
+ counts[e] = 0;
360
+ uniq[e] = new Set<string>();
361
+ }
362
+ for (const e of events) {
363
+ if (!FUNNEL_EVENTS.includes(e.event as FunnelEvent)) continue;
364
+ counts[e.event]++;
365
+ const k = (e.workspaceId as string | undefined) || (e.fingerprint as string | undefined) || String(e._id);
366
+ uniq[e.event].add(k);
367
+ }
368
+ const u = (n: string) => uniq[n]?.size || 0;
369
+ return {
370
+ counts,
371
+ unique: {
372
+ install: u("install"),
373
+ first_run: u("first_run"),
374
+ register_owner: u("register_owner"),
375
+ verify_code: u("verify_code"),
376
+ first_call_api_success: u("first_call_api_success"),
377
+ },
378
+ ratios: {
379
+ install_to_first_run: safeRatio(u("first_run"), u("install")),
380
+ first_run_to_register: safeRatio(u("register_owner"), u("first_run")),
381
+ register_to_verify: safeRatio(u("verify_code"), u("register_owner")),
382
+ verify_to_first_call: safeRatio(u("first_call_api_success"), u("verify_code")),
383
+ install_to_verify: safeRatio(u("verify_code"), u("install")),
384
+ install_to_first_call: safeRatio(u("first_call_api_success"), u("install")),
385
+ },
386
+ };
387
+ }
388
+
389
+ // Diagnostics-only query — reasons for drop-off and errors.
390
+ export const getDiagnostics = query({
391
+ args: {
392
+ hoursBack: v.optional(v.number()),
393
+ classification: v.optional(v.string()),
394
+ },
395
+ handler: async (ctx, args) => {
396
+ const windowH = args.hoursBack ?? 24 * 7;
397
+ const since = Date.now() - windowH * 3600000;
398
+ const cls = args.classification ?? "human";
399
+
400
+ const events = await ctx.db
401
+ .query("funnelEvents")
402
+ .withIndex("by_timestamp", (q) => q.gte("timestamp", since))
403
+ .collect();
404
+
405
+ const filtered = events.filter(
406
+ (e) => e.classification === cls && DIAGNOSTIC_EVENTS.includes(e.event as DiagnosticEvent)
407
+ );
408
+
409
+ const breakdown: Record<string, Record<string, number>> = {};
410
+ for (const e of filtered) {
411
+ breakdown[e.event] = breakdown[e.event] || {};
412
+ const reason = ((e.props as any)?.reason ?? (e.props as any)?.errorCode ?? "unknown") as string;
413
+ breakdown[e.event][reason] = (breakdown[e.event][reason] || 0) + 1;
414
+ }
415
+
416
+ return {
417
+ windowHours: windowH,
418
+ classification: cls,
419
+ total: filtered.length,
420
+ byEvent: breakdown,
421
+ };
422
+ },
423
+ });
424
+
425
+ // Quick listing for debugging.
426
+ export const getRecent = query({
427
+ args: { limit: v.optional(v.number()) },
428
+ handler: async (ctx, { limit = 100 }) => {
429
+ return await ctx.db.query("funnelEvents").order("desc").take(limit);
430
+ },
431
+ });
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Registration enforcement guards — single source of truth.
3
+ *
4
+ * Every call path that "should require registration" resolves through
5
+ * requireVerifiedOwner. Free paths (discover_apis, catalog, docs) do NOT
6
+ * call this. See Apiclaw-TOOLS.md for the enforcement matrix.
7
+ */
8
+ import { query } from "./_generated/server";
9
+ import { v } from "convex/values";
10
+ import type { Id } from "./_generated/dataModel";
11
+
12
+ export type VerifiedOwner = {
13
+ ok: true;
14
+ workspaceId: Id<"workspaces">;
15
+ email: string;
16
+ tier: string;
17
+ status: string;
18
+ usageCount: number;
19
+ usageLimit: number;
20
+ usageRemaining: number;
21
+ };
22
+
23
+ export type OwnerDenial = {
24
+ ok: false;
25
+ reason:
26
+ | "no_session"
27
+ | "session_invalid"
28
+ | "workspace_missing"
29
+ | "not_verified" // status !== active OR email missing
30
+ | "quota_exceeded";
31
+ message: string;
32
+ };
33
+
34
+ // Resolve a verified-owner decision from a session token.
35
+ // Pure read; no mutations. Returns a typed discriminated union so callers
36
+ // must handle both branches explicitly.
37
+ export async function resolveVerifiedOwner(
38
+ ctx: any,
39
+ sessionToken: string | null | undefined,
40
+ opts?: { allowQuotaExceeded?: boolean }
41
+ ): Promise<VerifiedOwner | OwnerDenial> {
42
+ if (!sessionToken) {
43
+ return {
44
+ ok: false,
45
+ reason: "no_session",
46
+ message:
47
+ "Registration required. Call register_owner({ email }) then verify_code({ email, code }).",
48
+ };
49
+ }
50
+
51
+ const session = await ctx.db
52
+ .query("agentSessions")
53
+ .withIndex("by_sessionToken", (q: any) => q.eq("sessionToken", sessionToken))
54
+ .first();
55
+
56
+ if (!session) {
57
+ return { ok: false, reason: "session_invalid", message: "Session not found or expired." };
58
+ }
59
+
60
+ const workspace = await ctx.db.get(session.workspaceId);
61
+ if (!workspace) {
62
+ return { ok: false, reason: "workspace_missing", message: "Workspace not found." };
63
+ }
64
+
65
+ if (workspace.status !== "active") {
66
+ return {
67
+ ok: false,
68
+ reason: "not_verified",
69
+ message: `Workspace status: ${workspace.status}. Verify your email to activate.`,
70
+ };
71
+ }
72
+
73
+ if (!workspace.email) {
74
+ return {
75
+ ok: false,
76
+ reason: "not_verified",
77
+ message: "Workspace has no verified email. Run register_owner + verify_code.",
78
+ };
79
+ }
80
+
81
+ const usageRemaining =
82
+ workspace.usageLimit > 0 ? workspace.usageLimit - workspace.usageCount : -1;
83
+
84
+ if (!opts?.allowQuotaExceeded && usageRemaining === 0) {
85
+ return {
86
+ ok: false,
87
+ reason: "quota_exceeded",
88
+ message: "Free tier quota exceeded. Upgrade at https://apiclaw.cloud/upgrade.",
89
+ };
90
+ }
91
+
92
+ return {
93
+ ok: true,
94
+ workspaceId: session.workspaceId,
95
+ email: workspace.email,
96
+ tier: workspace.tier,
97
+ status: workspace.status,
98
+ usageCount: workspace.usageCount,
99
+ usageLimit: workspace.usageLimit,
100
+ usageRemaining,
101
+ };
102
+ }
103
+
104
+ // Variant: verify by workspaceId directly (for API-key auth paths that already
105
+ // resolved a workspace from sk-claw-* and just need to confirm it's active+verified).
106
+ export async function resolveVerifiedOwnerByWorkspaceId(
107
+ ctx: any,
108
+ workspaceId: string | null | undefined,
109
+ opts?: { allowQuotaExceeded?: boolean }
110
+ ): Promise<VerifiedOwner | OwnerDenial> {
111
+ if (!workspaceId) {
112
+ return { ok: false, reason: "no_session", message: "No workspace resolved from API key." };
113
+ }
114
+ const workspace = await ctx.db.get(workspaceId as Id<"workspaces">);
115
+ if (!workspace) {
116
+ return { ok: false, reason: "workspace_missing", message: "Workspace not found." };
117
+ }
118
+ if (workspace.status !== "active") {
119
+ return {
120
+ ok: false,
121
+ reason: "not_verified",
122
+ message: `Workspace status: ${workspace.status}. Verify your email to activate.`,
123
+ };
124
+ }
125
+ if (!workspace.email) {
126
+ return { ok: false, reason: "not_verified", message: "Workspace has no verified email." };
127
+ }
128
+ const usageRemaining =
129
+ workspace.usageLimit > 0 ? workspace.usageLimit - workspace.usageCount : -1;
130
+ if (!opts?.allowQuotaExceeded && usageRemaining === 0) {
131
+ return {
132
+ ok: false,
133
+ reason: "quota_exceeded",
134
+ message: "Free tier quota exceeded. Upgrade at https://apiclaw.cloud/upgrade.",
135
+ };
136
+ }
137
+ return {
138
+ ok: true,
139
+ workspaceId: workspaceId as Id<"workspaces">,
140
+ email: workspace.email,
141
+ tier: workspace.tier,
142
+ status: workspace.status,
143
+ usageCount: workspace.usageCount,
144
+ usageLimit: workspace.usageLimit,
145
+ usageRemaining,
146
+ };
147
+ }
148
+
149
+ // Public query wrapper so HTTP handlers (which can only call queries/mutations)
150
+ // can invoke the guard. Returns a JSON-safe shape.
151
+ export const checkVerifiedOwnerByWorkspaceId = query({
152
+ args: {
153
+ workspaceId: v.optional(v.id("workspaces")),
154
+ allowQuotaExceeded: v.optional(v.boolean()),
155
+ },
156
+ handler: async (ctx, args) => {
157
+ return await resolveVerifiedOwnerByWorkspaceId(ctx, args.workspaceId, {
158
+ allowQuotaExceeded: args.allowQuotaExceeded,
159
+ });
160
+ },
161
+ });
162
+
163
+ export const checkVerifiedOwner = query({
164
+ args: {
165
+ sessionToken: v.optional(v.string()),
166
+ allowQuotaExceeded: v.optional(v.boolean()),
167
+ },
168
+ handler: async (ctx, args) => {
169
+ const result = await resolveVerifiedOwner(ctx, args.sessionToken, {
170
+ allowQuotaExceeded: args.allowQuotaExceeded,
171
+ });
172
+ return result;
173
+ },
174
+ });