@vllnt/convex-helpers 0.1.0 → 0.1.1-canary.3463ec8

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/CHANGELOG.md ADDED
@@ -0,0 +1,52 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Fixed
11
+
12
+ - Fail closed on thrown or stalled MCP authorization hooks; bound auth/lifecycle
13
+ callbacks to 10 seconds and remove raw exception logging.
14
+ - Add optional host-configured `AuthCtx.trustedIssuer` enforcement before identity
15
+ row callbacks, preserving the legacy single-issuer contract when omitted.
16
+ - Reject unsafe preview patterns, localhost paths/normalization and control characters;
17
+ validate cookie origins instead of trusting a prefix.
18
+ - Bound retargeting to 1000 rows with sequential callbacks and failure short-circuiting.
19
+ - Remove release-note shell interpolation; gate stable dispatch to main and explicit
20
+ `RELEASE_ENABLED=true`, and remove workflow-wide write/OIDC privileges.
21
+ - Patch development Handlebars and Vite/esbuild advisory paths; document the remaining
22
+ deepmerge-ts tooling advisory in `docs/READINESS.md`.
23
+
24
+ - Convert MCP `int64` and `bytes` inputs to native Convex values and serialize native Convex
25
+ results with lossless tagged JSON.
26
+ - Enforce resource argument validators before dispatch and reject unsafe mutation/action
27
+ timeouts that could report failure while non-cancellable side effects continue.
28
+
29
+ ### Changed
30
+
31
+ - Document actual shipped APIs and host-owned identity/merge/CSRF boundaries; identity
32
+ integration fixtures now receive strict lint checks (legacy MCP fixtures remain excluded).
33
+
34
+ - Refresh all direct dependencies to their latest compatible releases for canary validation.
35
+ - Require `convex@^1.45.0` and update `convex-test` to `^0.0.56`.
36
+
37
+ ### Added
38
+
39
+ - `./better-auth` — fail-closed trusted-origin parser + HTTPS cookie settings for `@convex-dev/better-auth` (does not import better-auth).
40
+ - `./identity` — `getOrCreateFromAuth` / `requireFromAuth` / `retargetRows` host-`ctx` glue for anonymous sessions and anonymous→identified upgrades.
41
+ - `./mcp` entry — expose Convex functions as MCP tools (`createMCPServer` + `query`/`mutation`/`action`/`resource`), default-deny auth, lifecycle hooks, validator→zod conversion, and optional HMAC-signed cursor pagination. Absorbed from `@vllnt/convex-mcp` (see ROADMAP `absorb-convex-mcp`). `@modelcontextprotocol/sdk` and `zod` are optional peer deps — the `./mcp` entry is tree-shakeable, so backend-only consumers pull neither. 100% test coverage retained (161 tests).
42
+
43
+ ## [0.1.0] - 2026-06-13
44
+
45
+ ### Added
46
+
47
+ - Scaffolded to fleet Universal standard (type-B helpers library)
48
+ - Seed root utilities: `asyncMap`, `pruneNull`, `nullThrows`, `NullDocumentError`
49
+ - 100% test coverage gate via vitest thresholds
50
+ - CI workflow, publish workflow, email-guard workflow
51
+ - Full docs set: README, CHANGELOG, CONTRIBUTING, SECURITY, CODE_OF_CONDUCT
52
+ - `llms.txt` and `llms-full.txt` for AI agent discovery
package/README.md CHANGED
@@ -1,12 +1,13 @@
1
1
  <!-- Badges -->
2
+
2
3
  [![npm version](https://img.shields.io/npm/v/@vllnt/convex-helpers.svg)](https://www.npmjs.com/package/@vllnt/convex-helpers)
3
4
  [![CI](https://github.com/vllnt/convex-helpers/actions/workflows/ci.yml/badge.svg)](https://github.com/vllnt/convex-helpers/actions/workflows/ci.yml)
4
5
  [![License: MIT](https://img.shields.io/npm/l/@vllnt/convex-helpers.svg)](./LICENSE)
5
6
 
6
7
  # @vllnt/convex-helpers
7
8
 
8
- Typed host-side helpers for Convex backends — builders, errors, validators, relationships,
9
- pagination, HTTP, env, and observability.
9
+ Typed Convex host-side utilities, trusted-origin and cookie configuration
10
+ helpers, identity-row glue, and optional MCP tools.
10
11
 
11
12
  ```ts
12
13
  import { asyncMap, pruneNull, nullThrows } from "@vllnt/convex-helpers";
@@ -15,9 +16,10 @@ const docs = pruneNull(await asyncMap(ids, (id) => ctx.db.get(id)));
15
16
  const doc = nullThrows(await ctx.db.get(id), `Document ${id} not found`);
16
17
  ```
17
18
 
18
- A helpers library (not a sandboxed Convex component): pure functions and host-`ctx` glue that run with
19
- the host's `ctx` — no own tables, no `app.use()` mounting. Stateful concerns (rate limiting,
20
- idempotency, flags) belong in `@convex-dev/*` or `@vllnt/convex-*` components.
19
+ A helpers library (not a sandboxed Convex component): pure functions and
20
+ host-`ctx` glue that run with the host's `ctx` — no own tables, no `app.use()`
21
+ mounting. Stateful concerns (rate limiting, idempotency, flags) belong in
22
+ `@convex-dev/*` or `@vllnt/convex-*` components.
21
23
 
22
24
  See [ROADMAP.md](./ROADMAP.md) for the planned module surface.
23
25
 
@@ -26,14 +28,20 @@ See [ROADMAP.md](./ROADMAP.md) for the planned module surface.
26
28
  - `asyncMap` — parallel async map that preserves order
27
29
  - `pruneNull` — filter null/undefined from arrays
28
30
  - `nullThrows` — non-null assertion with typed `NullDocumentError`
29
- - `./mcp` — expose Convex functions as MCP tools (`createMCPServer` + `query`/`mutation`/`action`/`resource`), default-deny auth, optional cursor pagination
30
- - [planned] `./builders` — `customQuery`/`customMutation`/`customAction`/`customCtx`
31
+ - `./better-auth` — fail-closed trusted origins + HTTPS cookies for better-auth
32
+ - `./identity` — identity-row lookup/bootstrap and bounded row-callback counting
33
+ - `./mcp` — expose Convex functions as MCP tools (`createMCPServer` +
34
+ `query`/`mutation`/`action`/`resource`), default-deny auth, optional cursor
35
+ pagination
36
+ - [planned] `./builders` —
37
+ `customQuery`/`customMutation`/`customAction`/`customCtx`
31
38
  - [planned] `./errors` — typed `AppError` + HTTP-status map
32
- - [planned] `./auth` — provider-agnostic `requireIdentity`/`getCurrentSubject`
33
39
  - [planned] `./env` — `defineEnv(zodSchema)` cold-start validation
34
- - [planned] `./tracing` — span emit + `traceparent` propagation via `@vllnt/logger`
40
+ - [planned] `./tracing` — span emit + `traceparent` propagation via
41
+ `@vllnt/logger`
35
42
  - [planned] `./testing` — fixture factories + `withIdentity`
36
- - [planned] `./relationships`, `./validators`, `./pagination`, `./rls`, `./triggers`, `./http`
43
+ - [planned] `./relationships`, `./validators`, `./pagination`, `./rls`,
44
+ `./triggers`, `./http`
37
45
  - [planned] `./react` — optional tree-shakeable front-end hooks layer
38
46
 
39
47
  ## Installation
@@ -42,7 +50,19 @@ See [ROADMAP.md](./ROADMAP.md) for the planned module surface.
42
50
  pnpm add @vllnt/convex-helpers
43
51
  ```
44
52
 
45
- `convex` is a peer dependency:
53
+ This README describes current `main`. npm `latest` is `0.1.0` and includes the
54
+ root utilities and `./mcp`, but **not** `./better-auth` or `./identity`. To use
55
+ those entries, install the prerelease channel (`0.1.1-canary.ba6c009` at this
56
+ audit):
57
+
58
+ ```bash
59
+ pnpm add @vllnt/convex-helpers@canary
60
+ ```
61
+
62
+ Canary tags move; pin the resolved version and test before production use.
63
+ Modules marked **planned** are not exported by either channel.
64
+
65
+ `convex@^1.45.0` is a peer dependency:
46
66
 
47
67
  ```bash
48
68
  pnpm add convex
@@ -62,8 +82,9 @@ const doc = nullThrows(await ctx.db.get(id), `Document ${id} not found`);
62
82
 
63
83
  ### MCP tools — `./mcp`
64
84
 
65
- Expose Convex functions to LLM agents over the Model Context Protocol. The `./mcp` entry is
66
- tree-shakeable — backend-only consumers pull zero MCP code. It needs two optional peer deps:
85
+ Expose Convex functions to LLM agents over the Model Context Protocol. The
86
+ `./mcp` entry is tree-shakeable — backend-only consumers pull zero MCP code. It
87
+ needs two optional peer deps:
67
88
 
68
89
  ```bash
69
90
  pnpm add @modelcontextprotocol/sdk zod
@@ -77,7 +98,10 @@ import { v } from "convex/values";
77
98
  export const mcp = createMCPServer({
78
99
  auth: { validate: async (key) => key === process.env.MCP_API_KEY },
79
100
  tools: {
80
- list_projects: query(api.projects.list, { args: v.object({}), description: "List all projects" }),
101
+ list_projects: query(api.projects.list, {
102
+ args: v.object({}),
103
+ description: "List all projects",
104
+ }),
81
105
  create_project: mutation(api.projects.create, {
82
106
  args: v.object({ name: v.string() }),
83
107
  description: "Create a project",
@@ -89,12 +113,96 @@ export const mcp = createMCPServer({
89
113
  export const { GET, POST } = mcp.handler();
90
114
  ```
91
115
 
92
- Migrating from `@vllnt/convex-mcp`? Change the import to `@vllnt/convex-helpers/mcp` — the API is
93
- identical. See [docs/API.md](./docs/API.md#mcp-tools-mcp) for the full `./mcp` reference.
116
+ MCP auth and lifecycle callbacks have a 10-second deadline per callback. A
117
+ thrown or timed-out `before` hook denies dispatch with a generic message. Auth
118
+ failures also deny access generically. Success/error hooks cannot undo completed
119
+ dispatch. Timeouts stop waiting, not the host callback; callbacks must avoid
120
+ side effects. Raw errors are not logged by the library; hosts may observe hook
121
+ context and must redact errors, arguments and credentials before logging.
122
+ Resource failures are masked without raw logging.
123
+
124
+ ### Better-auth origins — `./better-auth`
125
+
126
+ Fail-closed trusted-origin parsing and HTTPS cookie attributes. Does **not**
127
+ import `better-auth` — the host still calls `betterAuth({...})`.
128
+
129
+ ```ts
130
+ import {
131
+ cookieSettingsForSite,
132
+ trustedOriginsFromCsv,
133
+ } from "@vllnt/convex-helpers/better-auth";
134
+
135
+ const trustedOrigins = trustedOriginsFromCsv(
136
+ process.env.CONVEX_SITE_URL ?? "http://localhost:3211",
137
+ process.env.BETTER_AUTH_TRUSTED_ORIGINS ?? "",
138
+ );
139
+ ```
140
+
141
+ `parseTrustedOrigin` rejects credentials, paths, query/hash, controls and
142
+ arbitrary wildcards. HTTP is allowed only for exact localhost/127.0.0.1 origins.
143
+ An explicit `previewPattern` permits only HTTPS patterns shaped like
144
+ `https://app-*-org.example.com` (one wildcard inside a prefixed/suffixed first
145
+ label). The host must trust **every** deployment matched by its auth provider's
146
+ wildcard semantics; syntax validation does not establish deployment ownership.
147
+ Invalid extras are discarded; if none survive, the list helpers return
148
+ `undefined`, so the host omits `trustedOrigins` and retains Better Auth
149
+ defaults. They do not validate the host's entire auth configuration.
150
+ `cookieSettingsForSite(siteUrl)` returns secure, HttpOnly, SameSite=None
151
+ attributes for a valid HTTPS origin only; it does not replace CSRF/origin
152
+ protection and is for hosts requiring cross-site cookies.
153
+
154
+ ### Identity — `./identity`
155
+
156
+ Map `ctx.auth.getUserIdentity()` to a host row. The host must configure a
157
+ trusted single issuer (subjects are issuer-local). To enforce it locally, pass
158
+ `{ auth: ctx.auth, trustedIssuer: "https://your-trusted-issuer.example" }` as
159
+ the helper context. A mismatched or missing issuer rejects before lookup/insert.
160
+ The issuer must be host configuration, never a request argument. Omitting it
161
+ preserves compatibility and relies on the host's single-issuer auth
162
+ configuration. Provide callbacks bound to the same Convex mutation transaction,
163
+ including the indexed lookup, for race-safe bootstrap. Every competing creator
164
+ must use the same lookup. Actions or remote callbacks are not race-safe.
165
+ `isAnonymous` reflects only a literal `true` JWT claim; missing/false claims do
166
+ not prove a verified or identified account.
167
+
168
+ `retargetRows(rows, apply)` processes at most 1000 rows sequentially, counts
169
+ `patched`/`deleted`/`skipped`, and propagates failures without starting later
170
+ rows. The host supplies bounded pages, authorization for both identities,
171
+ conflict rules, continuation, transaction/rollback and logging. It is **not** a
172
+ secure account merge. These helpers neither construct `betterAuth` nor install
173
+ its anonymous plugin.
174
+
175
+ ```ts
176
+ import {
177
+ getOrCreateFromAuth,
178
+ retargetRows,
179
+ } from "@vllnt/convex-helpers/identity";
180
+
181
+ const user = await getOrCreateFromAuth(ctx, {
182
+ lookup: (subject) =>
183
+ ctx.db
184
+ .query("users")
185
+ .withIndex("by_betterauth_id", (q) => q.eq("betterAuthId", subject))
186
+ .unique(),
187
+ insert: async (subject) => {
188
+ const id = await ctx.db.insert("users", { betterAuthId: subject });
189
+ return (await ctx.db.get(id))!;
190
+ },
191
+ });
192
+ ```
193
+
194
+ Migrating from `@vllnt/convex-mcp`? Use `@vllnt/convex-helpers/mcp` and
195
+ explicitly install `@modelcontextprotocol/sdk@^1.29.0` and `zod@^4.3.6`
196
+ (optional peers here, regular dependencies in the legacy package). Helpers
197
+ requires `convex@^1.45.0` and is ESM-only; the legacy package also provides
198
+ CommonJS. Review current callback/security behavior above rather than assuming
199
+ an import-only migration. See [docs/API.md](./docs/API.md#mcp-tools-mcp) for the
200
+ full `./mcp` reference.
94
201
 
95
202
  ## API Reference
96
203
 
97
- See [docs/API.md](./docs/API.md) for full API reference with signatures and examples.
204
+ See [docs/API.md](./docs/API.md) for full API reference with signatures and
205
+ examples.
98
206
 
99
207
  ## Testing
100
208
 
@@ -103,17 +211,31 @@ pnpm test
103
211
  pnpm test:coverage # must reach 100%
104
212
  ```
105
213
 
106
- Tests use [vitest](https://vitest.dev) with the node environment. 100% coverage is enforced via
107
- `vitest.config.mts` thresholds.
214
+ Tests use [vitest](https://vitest.dev) with the node environment. 100% coverage
215
+ is enforced via `vitest.config.mts` thresholds. Identity integration tests use
216
+ **convex-test mocks**; they do not prove real Better Auth sessions or anonymous
217
+ plugin integration. The separate `scripts/local-identity-proof.mjs` passed 16
218
+ concurrent real local-backend bootstrap mutations with an injected synthetic
219
+ identity (one row); this tests indexed OCC, not login. Consuming apps must
220
+ verify their actual auth integration independently.
221
+
222
+ ## Documentation and security
223
+
224
+ - [API reference](./docs/API.md) · [LLM index](./llms.txt) ·
225
+ [Changelog](./CHANGELOG.md)
226
+ - [Security policy and private reporting](./SECURITY.md)
227
+ - [Issues](https://github.com/vllnt/convex-helpers/issues) for non-sensitive
228
+ bugs
108
229
 
109
230
  ## Contributing
110
231
 
111
- See [CONTRIBUTING.md](./CONTRIBUTING.md) for development setup, code style, and PR guidelines.
232
+ See [CONTRIBUTING.md](./CONTRIBUTING.md) for development setup, code style, and
233
+ PR guidelines.
112
234
 
113
235
  ## Author
114
236
 
115
- Built by [bntvllnt](https://github.com/bntvllnt) · [bntvllnt.com](https://bntvllnt.com) · [X
116
- @bntvllnt](https://x.com/bntvllnt)
237
+ Built by [bntvllnt](https://github.com/bntvllnt) ·
238
+ [bntvllnt.com](https://bntvllnt.com) · [X @bntvllnt](https://x.com/bntvllnt)
117
239
 
118
240
  Part of the [@vllnt](https://github.com/vllnt) Convex component fleet —
119
241
  [vllnt.com](https://vllnt.com)
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Fail-closed origin and cookie helpers for `@convex-dev/better-auth`.
3
+ * Does not import better-auth — the host still constructs `betterAuth(...)`.
4
+ */
5
+ export type CookieSettings = {
6
+ advanced: {
7
+ defaultCookieAttributes: {
8
+ httpOnly: true;
9
+ sameSite: "none";
10
+ secure: true;
11
+ };
12
+ useSecureCookies: true;
13
+ };
14
+ };
15
+ /**
16
+ * Parse one origin. HTTPS, no credentials/path/query/hash, no wildcards
17
+ * except an exact `previewPattern` (e.g. `https://app-*-org.vercel.app`).
18
+ */
19
+ export declare function parseTrustedOrigin(origin: string, options?: {
20
+ previewPattern?: string;
21
+ }): string | undefined;
22
+ /**
23
+ * Merge `siteUrl` with extra origins. Returns `undefined` when nothing extra
24
+ * survived parsing — the host then omits `trustedOrigins`.
25
+ * `siteUrl` uses the same rules (localhost HTTP allowed).
26
+ */
27
+ export declare function trustedOriginsFromList(siteUrl: string, extra: readonly string[], options?: {
28
+ previewPattern?: string;
29
+ }): string[] | undefined;
30
+ export declare function trustedOriginsFromCsv(siteUrl: string, csv: string, options?: {
31
+ previewPattern?: string;
32
+ }): string[] | undefined;
33
+ /** Secure cross-site cookies when `siteUrl` is HTTPS; otherwise `undefined`. */
34
+ export declare function cookieSettingsForSite(siteUrl: string): CookieSettings | undefined;
35
+ //# sourceMappingURL=better-auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"better-auth.d.ts","sourceRoot":"","sources":["../src/better-auth.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,MAAM,cAAc,GAAG;IAC3B,QAAQ,EAAE;QACR,uBAAuB,EAAE;YACvB,QAAQ,EAAE,IAAI,CAAC;YACf,QAAQ,EAAE,MAAM,CAAC;YACjB,MAAM,EAAE,IAAI,CAAC;SACd,CAAC;QACF,gBAAgB,EAAE,IAAI,CAAC;KACxB,CAAC;CACH,CAAC;AAwDF;;;GAGG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,MAAM,EACd,OAAO,GAAE;IAAE,cAAc,CAAC,EAAE,MAAM,CAAA;CAAO,GACxC,MAAM,GAAG,SAAS,CAwBpB;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,OAAO,GAAE;IAAE,cAAc,CAAC,EAAE,MAAM,CAAA;CAAO,GACxC,MAAM,EAAE,GAAG,SAAS,CAUtB;AAED,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,OAAO,GAAE;IAAE,cAAc,CAAC,EAAE,MAAM,CAAA;CAAO,GACxC,MAAM,EAAE,GAAG,SAAS,CAEtB;AAED,gFAAgF;AAChF,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,MAAM,GACd,cAAc,GAAG,SAAS,CAiB5B"}
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Fail-closed origin and cookie helpers for `@convex-dev/better-auth`.
3
+ * Does not import better-auth — the host still constructs `betterAuth(...)`.
4
+ */
5
+ function hasControlCharacter(value) {
6
+ // Control-character detection is the point of this helper.
7
+ // eslint-disable-next-line no-control-regex -- C0 + DEL
8
+ return /[\u0000-\u001F\u007F]/u.test(value);
9
+ }
10
+ function isLocalHttp(origin) {
11
+ return (origin.startsWith("http://localhost") ||
12
+ origin.startsWith("http://127.0.0.1"));
13
+ }
14
+ function httpsOrigin(trimmed) {
15
+ try {
16
+ const url = new URL(trimmed);
17
+ if (url.protocol !== "https:" ||
18
+ url.username !== "" ||
19
+ url.password !== "" ||
20
+ url.pathname !== "/" ||
21
+ url.search !== "" ||
22
+ url.hash !== "" ||
23
+ (trimmed !== url.origin && trimmed !== `${url.origin}/`)) {
24
+ return undefined;
25
+ }
26
+ return url.origin;
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
32
+ function localHttpOrigin(trimmed) {
33
+ try {
34
+ const url = new URL(trimmed);
35
+ if (url.protocol !== "http:" ||
36
+ url.username !== "" ||
37
+ url.password !== "" ||
38
+ (url.hostname !== "localhost" && url.hostname !== "127.0.0.1") ||
39
+ url.pathname !== "/" ||
40
+ url.search !== "" ||
41
+ url.hash !== "" ||
42
+ (trimmed !== url.origin && trimmed !== `${url.origin}/`)) {
43
+ return undefined;
44
+ }
45
+ return url.origin;
46
+ }
47
+ catch {
48
+ return undefined;
49
+ }
50
+ }
51
+ /**
52
+ * Parse one origin. HTTPS, no credentials/path/query/hash, no wildcards
53
+ * except an exact `previewPattern` (e.g. `https://app-*-org.vercel.app`).
54
+ */
55
+ export function parseTrustedOrigin(origin, options = {}) {
56
+ const trimmed = origin.trim();
57
+ if (trimmed === "")
58
+ return undefined;
59
+ if (hasControlCharacter(origin))
60
+ return undefined;
61
+ if (options.previewPattern !== undefined &&
62
+ trimmed === options.previewPattern &&
63
+ /^https:\/\/[a-z0-9]+(?:-[a-z0-9]+)*-\*-[a-z0-9]+(?:-[a-z0-9]+)*(?:\.[a-z0-9]+(?:-[a-z0-9]+)*){2,}$/u.test(trimmed)) {
64
+ return trimmed;
65
+ }
66
+ if (isLocalHttp(trimmed)) {
67
+ return localHttpOrigin(trimmed);
68
+ }
69
+ if (!trimmed.startsWith("https://") ||
70
+ trimmed.includes("*") ||
71
+ trimmed.includes("?")) {
72
+ return undefined;
73
+ }
74
+ return httpsOrigin(trimmed);
75
+ }
76
+ /**
77
+ * Merge `siteUrl` with extra origins. Returns `undefined` when nothing extra
78
+ * survived parsing — the host then omits `trustedOrigins`.
79
+ * `siteUrl` uses the same rules (localhost HTTP allowed).
80
+ */
81
+ export function trustedOriginsFromList(siteUrl, extra, options = {}) {
82
+ const parsed = extra
83
+ .map((origin) => parseTrustedOrigin(origin, options))
84
+ .filter((origin) => origin !== undefined);
85
+ if (parsed.length === 0)
86
+ return undefined;
87
+ const site = parseTrustedOrigin(siteUrl, options);
88
+ if (site === undefined) {
89
+ return parsed;
90
+ }
91
+ return [site, ...parsed];
92
+ }
93
+ export function trustedOriginsFromCsv(siteUrl, csv, options = {}) {
94
+ return trustedOriginsFromList(siteUrl, csv.split(","), options);
95
+ }
96
+ /** Secure cross-site cookies when `siteUrl` is HTTPS; otherwise `undefined`. */
97
+ export function cookieSettingsForSite(siteUrl) {
98
+ if (!siteUrl.startsWith("https://") ||
99
+ parseTrustedOrigin(siteUrl) === undefined) {
100
+ return undefined;
101
+ }
102
+ return {
103
+ advanced: {
104
+ defaultCookieAttributes: {
105
+ httpOnly: true,
106
+ sameSite: "none",
107
+ secure: true,
108
+ },
109
+ useSecureCookies: true,
110
+ },
111
+ };
112
+ }
113
+ //# sourceMappingURL=better-auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"better-auth.js","sourceRoot":"","sources":["../src/better-auth.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAaH,SAAS,mBAAmB,CAAC,KAAa;IACxC,2DAA2D;IAC3D,wDAAwD;IACxD,OAAO,wBAAwB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC9C,CAAC;AAED,SAAS,WAAW,CAAC,MAAc;IACjC,OAAO,CACL,MAAM,CAAC,UAAU,CAAC,kBAAkB,CAAC;QACrC,MAAM,CAAC,UAAU,CAAC,kBAAkB,CAAC,CACtC,CAAC;AACJ,CAAC;AAED,SAAS,WAAW,CAAC,OAAe;IAClC,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC;QAC7B,IACE,GAAG,CAAC,QAAQ,KAAK,QAAQ;YACzB,GAAG,CAAC,QAAQ,KAAK,EAAE;YACnB,GAAG,CAAC,QAAQ,KAAK,EAAE;YACnB,GAAG,CAAC,QAAQ,KAAK,GAAG;YACpB,GAAG,CAAC,MAAM,KAAK,EAAE;YACjB,GAAG,CAAC,IAAI,KAAK,EAAE;YACf,CAAC,OAAO,KAAK,GAAG,CAAC,MAAM,IAAI,OAAO,KAAK,GAAG,GAAG,CAAC,MAAM,GA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B,kBAAkB,CAAC,OAAO,CAAC,KAAK,SAAS,EACzC,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO;QACL,QAAQ,EAAE;YACR,uBAAuB,EAAE;gBACvB,QAAQ,EAAE,IAAI;gBACd,QAAQ,EAAE,MAAM;gBAChB,MAAM,EAAE,IAAI;aACb;YACD,gBAAgB,EAAE,IAAI;SACvB;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Host-ctx identity glue: map `ctx.auth` to a host row, and retarget rows when
3
+ * an anonymous subject upgrades. Writes the **host's** tables — not a component.
4
+ */
5
+ export type AuthIdentity = {
6
+ isAnonymous?: unknown;
7
+ issuer?: string;
8
+ subject: string;
9
+ };
10
+ export type AuthCtx = {
11
+ auth: {
12
+ getUserIdentity: () => Promise<AuthIdentity | null>;
13
+ };
14
+ /** Host-configured issuer; never accept this value from request arguments. */
15
+ trustedIssuer?: string;
16
+ };
17
+ export declare function isAnonymousIdentity(identity: AuthIdentity): boolean;
18
+ export declare function requireIdentity(ctx: AuthCtx): Promise<AuthIdentity>;
19
+ /**
20
+ * Query-side lookup. Returns null when unauthenticated or the host row is not
21
+ * there yet (BetterAuth `onCreate` can lag a fresh anonymous session).
22
+ */
23
+ export declare function getFromAuth<T extends object>(ctx: AuthCtx, lookup: (subject: string) => Promise<null | T>): Promise<null | (T & {
24
+ isAnonymous: boolean;
25
+ })>;
26
+ export declare function requireFromAuth<T extends object>(ctx: AuthCtx, lookup: (subject: string) => Promise<null | T>): Promise<T & {
27
+ isAnonymous: boolean;
28
+ }>;
29
+ /**
30
+ * Mutation-side: look up the host row for the current identity, or insert it.
31
+ * Atomic when both callbacks use the SAME Convex mutation transaction,
32
+ * including an indexed lookup; every competing writer must use that lookup.
33
+ * Actions, remote calls and nontransactional callbacks do not provide uniqueness.
34
+ */
35
+ export declare function getOrCreateFromAuth<T extends object>(ctx: AuthCtx, handlers: {
36
+ insert: (subject: string) => Promise<T>;
37
+ lookup: (subject: string) => Promise<null | T>;
38
+ }): Promise<T & {
39
+ isAnonymous: boolean;
40
+ }>;
41
+ /**
42
+ * Process at most 1000 rows sequentially (one callback in flight).
43
+ * The host owns authorization, page size, continuation, conflict resolution and
44
+ * transaction boundaries. This is not an account merge or ownership check.
45
+ */
46
+ export declare function retargetRows<T>(rows: readonly T[], apply: (row: T) => Promise<"deleted" | "patched" | "skipped">): Promise<{
47
+ deleted: number;
48
+ patched: number;
49
+ skipped: number;
50
+ }>;
51
+ //# sourceMappingURL=identity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,MAAM,MAAM,YAAY,GAAG;IACzB,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG;IACpB,IAAI,EAAE;QACJ,eAAe,EAAE,MAAM,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC;KACrD,CAAC;IACF,8EAA8E;IAC9E,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,YAAY,GAAG,OAAO,CAEnE;AAcD,wBAAsB,eAAe,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,YAAY,CAAC,CAUzE;AAED;;;GAGG;AACH,wBAAsB,WAAW,CAAC,CAAC,SAAS,MAAM,EAChD,GAAG,EAAE,OAAO,EACZ,MAAM,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,GAAG,CAAC,CAAC,GAC7C,OAAO,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG;IAAE,WAAW,EAAE,OAAO,CAAA;CAAE,CAAC,CAAC,CAOhD;AAED,wBAAsB,eAAe,CAAC,CAAC,SAAS,MAAM,EACpD,GAAG,EAAE,OAAO,EACZ,MAAM,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,GAAG,CAAC,CAAC,GAC7C,OAAO,CAAC,CAAC,GAAG;IAAE,WAAW,EAAE,OAAO,CAAA;CAAE,CAAC,CASvC;AAED;;;;;GAKG;AACH,wBAAsB,mBAAmB,CAAC,CAAC,SAAS,MAAM,EACxD,GAAG,EAAE,OAAO,EACZ,QAAQ,EAAE;IACR,MAAM,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;IACxC,MAAM,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC;CAChD,GACA,OAAO,CAAC,CAAC,GAAG;IAAE,WAAW,EAAE,OAAO,CAAA;CAAE,CAAC,CAKvC;AAED;;;;GAIG;AACH,wBAAsB,YAAY,CAAC,CAAC,EAClC,IAAI,EAAE,SAAS,CAAC,EAAE,EAClB,KAAK,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,OAAO,CAAC,SAAS,GAAG,SAAS,GAAG,SAAS,CAAC,GAC5D,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CAchE"}
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Host-ctx identity glue: map `ctx.auth` to a host row, and retarget rows when
3
+ * an anonymous subject upgrades. Writes the **host's** tables — not a component.
4
+ */
5
+ import { ConvexError } from "convex/values";
6
+ export function isAnonymousIdentity(identity) {
7
+ return identity.isAnonymous === true;
8
+ }
9
+ function assertTrustedIssuer(ctx, identity) {
10
+ if (ctx.trustedIssuer !== undefined &&
11
+ identity.issuer !== ctx.trustedIssuer) {
12
+ throw new ConvexError({
13
+ code: "UNAUTHENTICATED",
14
+ message: "Untrusted issuer.",
15
+ });
16
+ }
17
+ }
18
+ export async function requireIdentity(ctx) {
19
+ const identity = await ctx.auth.getUserIdentity();
20
+ if (identity === null) {
21
+ throw new ConvexError({
22
+ code: "UNAUTHENTICATED",
23
+ message: "Sign-in required.",
24
+ });
25
+ }
26
+ assertTrustedIssuer(ctx, identity);
27
+ return identity;
28
+ }
29
+ /**
30
+ * Query-side lookup. Returns null when unauthenticated or the host row is not
31
+ * there yet (BetterAuth `onCreate` can lag a fresh anonymous session).
32
+ */
33
+ export async function getFromAuth(ctx, lookup) {
34
+ const identity = await ctx.auth.getUserIdentity();
35
+ if (identity === null)
36
+ return null;
37
+ assertTrustedIssuer(ctx, identity);
38
+ const row = await lookup(identity.subject);
39
+ if (row === null)
40
+ return null;
41
+ return { ...row, isAnonymous: isAnonymousIdentity(identity) };
42
+ }
43
+ export async function requireFromAuth(ctx, lookup) {
44
+ const user = await getFromAuth(ctx, lookup);
45
+ if (user === null) {
46
+ throw new ConvexError({
47
+ code: "USER_NOT_INITIALIZED",
48
+ message: "User not initialized — the auth session may still be settling.",
49
+ });
50
+ }
51
+ return user;
52
+ }
53
+ /**
54
+ * Mutation-side: look up the host row for the current identity, or insert it.
55
+ * Atomic when both callbacks use the SAME Convex mutation transaction,
56
+ * including an indexed lookup; every competing writer must use that lookup.
57
+ * Actions, remote calls and nontransactional callbacks do not provide uniqueness.
58
+ */
59
+ export async function getOrCreateFromAuth(ctx, handlers) {
60
+ const identity = await requireIdentity(ctx);
61
+ const existing = await handlers.lookup(identity.subject);
62
+ const row = existing ?? (await handlers.insert(identity.subject));
63
+ return { ...row, isAnonymous: isAnonymousIdentity(identity) };
64
+ }
65
+ /**
66
+ * Process at most 1000 rows sequentially (one callback in flight).
67
+ * The host owns authorization, page size, continuation, conflict resolution and
68
+ * transaction boundaries. This is not an account merge or ownership check.
69
+ */
70
+ export async function retargetRows(rows, apply) {
71
+ if (rows.length > 1000) {
72
+ throw new RangeError("retargetRows accepts at most 1000 rows per page");
73
+ }
74
+ return rows.reduce(async (previous, row) => {
75
+ const counts = await previous;
76
+ const outcome = await apply(row);
77
+ return { ...counts, [outcome]: counts[outcome] + 1 };
78
+ }, Promise.resolve({ deleted: 0, patched: 0, skipped: 0 }));
79
+ }
80
+ //# sourceMappingURL=identity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity.js","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAgB5C,MAAM,UAAU,mBAAmB,CAAC,QAAsB;IACxD,OAAO,QAAQ,CAAC,WAAW,KAAK,IAAI,CAAC;AACvC,CAAC;AAED,SAAS,mBAAmB,CAAC,GAAY,EAAE,QAAsB;IAC/D,IACE,GAAG,CAAC,aAAa,KAAK,SAAS;QAC/B,QAAQ,CAAC,MAAM,KAAK,GAAG,CAAC,aAAa,EACrC,CAAC;QACD,MAAM,IAAI,WAAW,CAAC;YACpB,IAAI,EAAE,iBAAiB;YACvB,OAAO,EAAE,mBAAmB;SAC7B,CAAC,CAAC;IACL,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,GAAY;IAChD,MAAM,QAAQ,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC;IAClD,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;QACtB,MAAM,IAAI,WAAW,CAAC;YACpB,IAAI,EAAE,iBAAiB;YACvB,OAAO,EAAE,mBAAmB;SAC7B,CAAC,CAAC;IACL,CAAC;IACD,mBAAmB,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IACnC,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAC/B,GAAY,EACZ,MAA8C;IAE9C,MAAM,QAAQ,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC;IAClD,IAAI,QAAQ,KAAK,IAAI;QAAE,OAAO,IAAI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;IAC1E,CAAC;IACD,OAAO,IAAI,CAAC,MAAM,CAGhB,KAAK,EAAE,QAAQ,EAAE,GAAG,EAAE,EAAE;QACtB,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC;QAC9B,MAAM,OAAO,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC;QACjC,OAAO,EAAE,GAAG,MAAM,EAAE,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;IACvD,CAAC,EACD,OAAO,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,CACxD,CAAC;AACJ,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/mcp/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,wBAAgB,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CASlE;AAED,wBAAsB,eAAe,CACnC,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,UAAU,GACf,OAAO,CACN;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,IAAI,CAAA;CAAE,GACrD;IAAE,QAAQ,EAAE,QAAQ,CAAC;IAAC,KAAK,EAAE,KAAK,CAAA;CAAE,CACvC,CAiCA"}
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/mcp/auth.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,wBAAgB,aAAa,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CASlE;AAED,wBAAsB,eAAe,CACnC,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE,UAAU,GACf,OAAO,CACN;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,IAAI,CAAA;CAAE,GACrD;IAAE,QAAQ,EAAE,QAAQ,CAAC;IAAC,KAAK,EAAE,KAAK,CAAA;CAAE,CACvC,CA+CA"}
package/dist/mcp/auth.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { policyCallback } from "./callback.js";
1
2
  export function extractApiKey(request) {
2
3
  const authHeader = request.headers.get("authorization");
3
4
  if (!authHeader)
@@ -17,20 +18,32 @@ export async function validateRequest(request, auth) {
17
18
  valid: false,
18
19
  };
19
20
  }
20
- const isValid = await auth.validate(apiKey);
21
- if (!isValid) {
21
+ try {
22
+ const isValid = await policyCallback(() => auth.validate(apiKey));
23
+ if (!isValid) {
24
+ return {
25
+ response: new Response(JSON.stringify({ error: "Invalid API key." }), {
26
+ headers: { "Content-Type": "application/json" },
27
+ status: 401,
28
+ }),
29
+ valid: false,
30
+ };
31
+ }
32
+ let convexToken;
33
+ if (auth.convexToken) {
34
+ const resolveToken = auth.convexToken;
35
+ convexToken = await policyCallback(() => resolveToken(apiKey));
36
+ }
37
+ return { apiKey, convexToken, valid: true };
38
+ }
39
+ catch {
22
40
  return {
23
- response: new Response(JSON.stringify({ error: "Invalid API key." }), {
41
+ response: new Response(JSON.stringify({ error: "Authentication failed." }), {
24
42
  headers: { "Content-Type": "application/json" },
25
43
  status: 401,
26
44
  }),
27
45
  valid: false,
28
46
  };
29
47
  }
30
- let convexToken;
31
- if (auth.convexToken) {
32
- convexToken = await auth.convexToken(apiKey);
33
- }
34
- return { apiKey, convexToken, valid: true };
35
48
  }
36
49
  //# sourceMappingURL=auth.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../src/mcp/auth.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,aAAa,CAAC,OAAgB;IAC5C,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,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