@lupinum/better-convex-functions 0.1.0-rc.2 → 0.1.0-rc.4

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.
Files changed (65) hide show
  1. package/README.md +3 -0
  2. package/dist/agent/AGENTS.md +5 -4
  3. package/dist/agent/pages/docs/build/agents/limits.md +1 -0
  4. package/dist/agent/pages/docs/build/agents/mcp-apps.md +4 -2
  5. package/dist/agent/pages/docs/build/agents/mcp-door.md +164 -0
  6. package/dist/agent/pages/docs/build/application-behavior/devtools.md +6 -0
  7. package/dist/agent/pages/docs/build/application-behavior/error-handling.md +3 -1
  8. package/dist/agent/pages/docs/build/authentication/account-deletion.md +7 -0
  9. package/dist/agent/pages/docs/build/authentication/better-auth-setup.md +31 -2
  10. package/dist/agent/pages/docs/build/authentication/cacheable-public-pages.md +12 -0
  11. package/dist/agent/pages/docs/build/authentication/route-protection.md +17 -0
  12. package/dist/agent/pages/docs/build/authentication/sign-in-and-sign-out.md +2 -0
  13. package/dist/agent/pages/docs/build/authentication/transactional-email.md +5 -1
  14. package/dist/agent/pages/docs/build/files/upload-files.md +4 -0
  15. package/dist/agent/pages/docs/build/functions/internal-operations.md +80 -4
  16. package/dist/agent/pages/docs/build/functions/limits-and-audit.md +19 -9
  17. package/dist/agent/pages/docs/build/functions/policy-and-roles.md +34 -2
  18. package/dist/agent/pages/docs/build/functions/row-rules.md +18 -3
  19. package/dist/agent/pages/docs/build/functions/start-here.md +7 -0
  20. package/dist/agent/pages/docs/build/functions/threat-model.md +3 -1
  21. package/dist/agent/pages/docs/build/queries/pagination.md +13 -3
  22. package/dist/agent/pages/docs/build/queries/queries.md +2 -2
  23. package/dist/agent/pages/docs/build/queries/ssr-options.md +3 -3
  24. package/dist/agent/pages/docs/build/server/credentials-and-security.md +1 -1
  25. package/dist/agent/pages/docs/build/server/server-convex.md +4 -0
  26. package/dist/agent/pages/docs/build/server/server-routes.md +7 -3
  27. package/dist/agent/pages/docs/build/server/webhooks-and-jobs.md +5 -3
  28. package/dist/agent/pages/docs/concepts/errors-and-failures.md +1 -1
  29. package/dist/agent/pages/docs/concepts/request-lifecycle.md +1 -1
  30. package/dist/agent/pages/docs/concepts/server-and-client-boundaries.md +1 -1
  31. package/dist/agent/pages/docs/concepts/ssr-hydration-realtime.md +1 -1
  32. package/dist/agent/pages/docs/get-started/installation.md +5 -5
  33. package/dist/agent/pages/docs/get-started/plain-vue.md +101 -0
  34. package/dist/agent/pages/docs/operations/deploy-to-vercel.md +139 -62
  35. package/dist/agent/pages/docs/operations/deployment.md +49 -16
  36. package/dist/agent/pages/docs/operations/environment-variables.md +8 -5
  37. package/dist/agent/pages/docs/operations/release-compatibility.md +11 -2
  38. package/dist/agent/pages/docs/operations/upgrade-to-1-0.md +43 -1
  39. package/dist/agent/pages/docs/overview/comparison.md +4 -4
  40. package/dist/agent/pages/docs/overview/who-it-is-for.md +3 -3
  41. package/dist/agent/pages/docs/recipes/authenticated-server-route.md +3 -2
  42. package/dist/agent/pages/docs/recipes/error-messages.md +1 -1
  43. package/dist/agent/pages/docs/reference/api-surface.md +5 -5
  44. package/dist/agent/pages/docs/reference/composables.md +24 -5
  45. package/dist/agent/pages/docs/reference/error-types.md +3 -3
  46. package/dist/agent/pages/docs/reference/package-exports.md +3 -3
  47. package/dist/agent/pages/docs/reference/server-api.md +20 -11
  48. package/dist/index.d.mts +2 -2
  49. package/dist/index.d.ts +2 -2
  50. package/dist/index.mjs +3 -2
  51. package/dist/internal.d.mts +3 -3
  52. package/dist/internal.d.ts +3 -3
  53. package/dist/internal.mjs +3 -2
  54. package/dist/policy.d.mts +1 -1
  55. package/dist/policy.d.ts +1 -1
  56. package/dist/policy.mjs +1 -1
  57. package/dist/shared/better-convex-functions.Cls6oTe2.mjs +60 -0
  58. package/dist/shared/{better-convex-functions.BXyIEZ9W.mjs → better-convex-functions.D93COdqw.mjs} +175 -23
  59. package/dist/shared/{better-convex-functions.BagJR2Lk.d.mts → better-convex-functions.DPszvwmH.d.mts} +10 -4
  60. package/dist/shared/{better-convex-functions.BagJR2Lk.d.ts → better-convex-functions.DPszvwmH.d.ts} +10 -4
  61. package/dist/shared/{better-convex-functions.AOeEX0Gw.d.mts → better-convex-functions.DWLjNLAt.d.mts} +273 -80
  62. package/dist/shared/{better-convex-functions.D89tXIyj.d.ts → better-convex-functions.MRCy3IRt.d.ts} +273 -80
  63. package/dist/shared/{better-convex-functions.CkBcbT2F.mjs → better-convex-functions.WaldVS6e.mjs} +6 -4
  64. package/dist/test.mjs +2 -2
  65. package/package.json +1 -1
package/README.md CHANGED
@@ -88,6 +88,9 @@ export const fns = defineFunctions({
88
88
  .withIndex('by_auth_id', (q) => q.eq('authId', authId))
89
89
  .unique(),
90
90
  roleOf: async (ctx, user, tenant) => {
91
+ // A call that names no organization gets no role. What every signed-in person may do is a
92
+ // role too (see Policy and roles: signedIn).
93
+ if (tenant === null) return null
91
94
  if (tenant.table !== 'organizations') return null
92
95
  const membership = await ctx.db
93
96
  .query('memberships')
@@ -1,6 +1,6 @@
1
- # @lupinum/better-convex-functions 0.1.0-rc.2 documentation
1
+ # @lupinum/better-convex-functions 0.1.0-rc.4 documentation
2
2
 
3
- These pages describe the installed version 0.1.0-rc.2. Prefer them over the
3
+ These pages describe the installed version 0.1.0-rc.4. Prefer them over the
4
4
  website and over knowledge of earlier versions: the API changed during the 1.0 betas.
5
5
 
6
6
  ## Start here
@@ -8,15 +8,16 @@ website and over knowledge of earlier versions: the API changed during the 1.0 b
8
8
  | Task | Read in this order |
9
9
  | ---- | ------------------ |
10
10
  | Check who may do what in every Convex function | [Start here](./pages/docs/build/functions/start-here.md) → [Policy and roles](./pages/docs/build/functions/policy-and-roles.md) → [Row rules](./pages/docs/build/functions/row-rules.md) |
11
- | Run follow-up work, outside calls and crons | [Internal operations](./pages/docs/build/functions/internal-operations.md) |
11
+ | Run follow-up work, outside calls, public actions and crons | [Internal operations](./pages/docs/build/functions/internal-operations.md) |
12
12
  | Prove that nothing leaks and calls stay cheap | [Test your app](./pages/docs/build/functions/testing.md) → [Cost](./pages/docs/build/functions/cost.md) |
13
13
  | Know what is and is not protected | [Threat model](./pages/docs/build/functions/threat-model.md) |
14
14
  | Handle an error code | [Operation error codes](./pages/docs/reference/operation-error-codes.md) |
15
15
 
16
16
  ## Rules
17
17
 
18
- - Build every Convex function with `query`, `mutation`, `internalQuery`, `internalMutation`, `internalAction` or `job` from `defineFunctions`, never from `./_generated/server`. Wrap a function that must skip the library in `trusted(reason, fn)`, and keep the `unguardedFunctions` test green.
18
+ - Build every Convex function with `query`, `mutation`, `action`, `internalQuery`, `internalMutation`, `internalAction` or `job` from `defineFunctions`, never from `./_generated/server`. Create `action` once with `fns.action(internal.functions.authorizeAction)` and export `authorizeAction` from `fns`. Wrap a function that must skip the library in `trusted(reason, fn)`, and keep the `unguardedFunctions` test green.
19
19
  - Add an action to `policy.actions` before an operation uses it. Give every table a row rule; do not check membership in the handler.
20
+ - Never check a role in a handler or in a wrapper around the builders. `roleOf` gives every role: for the tenant a call names, and for `null` (a call that names none) the role outside any tenant, such as `signedIn`, or the role of the member in an app with one workspace. Answer `null` for a tenant you do not handle.
20
21
  - Read rows by an index that starts with the field the table rule checks (the tenant or owner field, or the `publicRead` condition). A query that returns a row the caller may not read fails.
21
22
  - An operation on an `anyOf` table names its tenant in its own arguments (`organizationId`).
22
23
  - Fail with `fail(code, message)` and an `ErrorCode`. Any other error reaches callers as a generic message.
@@ -38,6 +38,7 @@ In-app agent runs are experimental in 0.1: their API may change in a minor relea
38
38
  | Finished in-app agent runs | kept 30 days, with their messages | deleted by `housekeeping` |
39
39
  | Length of a tool name | 1 to 64 letters, digits, `_` or `-` | error when the module loads |
40
40
  | Text of an approval summary | one line, 300 characters | longer text is cut |
41
+ | Unclaimed upload links and files | 100 per agent connection | `RATE_LIMITED`; see [Files from agents](./mcp-door.md#files-from-agents) |
41
42
 
42
43
  Read tools have no rate limit. Convex's own limits apply to them, and a page
43
44
  reads at most 100 rows.
@@ -103,8 +103,10 @@ await writeFile(
103
103
  }
104
104
  ```
105
105
 
106
- Run `pnpm build:mcp-ui` before you run `pnpm exec better-convex convex dev` or
107
- `pnpm exec better-convex convex deploy`.
106
+ Run `pnpm build:mcp-ui` before you run `pnpm exec better-convex convex dev`,
107
+ and commit the generated `convex/mcp/notesCardHtml.ts`. A production build
108
+ that deploys Convex, as in [Deploy to Vercel](../../operations/deploy-to-vercel.md),
109
+ deploys the committed file.
108
110
 
109
111
  ## Connect the card to the host
110
112
 
@@ -157,6 +157,170 @@ Signing out of the application ends the session that granted consent, so it
157
157
  disconnects the person's hosts too. The person connects them again after the
158
158
  next sign-in.
159
159
 
160
+ ## Files from agents
161
+
162
+ An MCP request carries at most 64 KiB, so a file cannot travel inside a tool
163
+ call. An agent sends a file in three steps instead:
164
+
165
+ 1. It calls the built-in tool `request_upload` and gets one-time upload tokens.
166
+ 2. It sends each file's bytes to the application's upload route, with one token per file. The route answers with an `uploadId`.
167
+ 3. It calls one of your tools with the `uploadId`. The tool calls `claimUpload`, which hands it the stored file.
168
+
169
+ Only agents that can read local files and send HTTP requests can do this,
170
+ for example Claude Code or Codex. A chat app such as Claude on the web or
171
+ ChatGPT cannot send a file from the person's computer.
172
+
173
+ ### Why a claim
174
+
175
+ A storage ID gives whoever holds it the file (see
176
+ [Threat model](../functions/threat-model.md)). An `uploadId` does not.
177
+ `claimUpload` passes only when all of these are true:
178
+
179
+ - The call comes from the same actor that asked for the link: the same agent connection of the same person.
180
+ - The file was not claimed before.
181
+ - The file arrived less than 24 hours ago.
182
+ - The type and size are ones the tool allows. The route decides the type from the file's first bytes, never from its name.
183
+
184
+ A missing, foreign or already claimed upload fails with `NOT_FOUND`. A type or
185
+ size the tool does not allow fails with `INVALID_INPUT`, and the file stays
186
+ claimable for another call.
187
+
188
+ ### Turn uploads on
189
+
190
+ Add `uploads` to `defineTools`. `scopes` names the OAuth scopes whose
191
+ connections may ask for links; a read-only connection does not see the tool.
192
+ The samples in this section come from an expense app with an `expenses` table.
193
+
194
+ ```ts
195
+ // convex/agents.ts
196
+ import { defineTools } from '@lupinum/better-convex-agents'
197
+
198
+ import { internal } from './_generated/api'
199
+ import { fns } from './functions'
200
+ import * as receipts from './receipts'
201
+
202
+ export const tools = defineTools(
203
+ fns,
204
+ { receipts },
205
+ {
206
+ functions: internal.agents,
207
+ uploads: { scopes: ['write'], types: ['application/pdf'], maxBytes: 10 * 1024 * 1024 },
208
+ },
209
+ )
210
+
211
+ export const {
212
+ attach_receipt,
213
+ check_approval,
214
+ housekeeping,
215
+ request_upload,
216
+ upload_ticket,
217
+ upload_stored,
218
+ } = tools.functions
219
+ ```
220
+
221
+ `types` takes `application/pdf`, `image/png`, `image/jpeg`, `image/webp` and
222
+ `text/csv`. A CSV file has no signature: the route accepts UTF-8 text without
223
+ control characters other than tab and line breaks, and your parser checks the
224
+ rest. `maxBytes` is at most 20 MiB, the request limit of a Convex HTTP action.
225
+
226
+ Add the upload route to `convex/http.ts`, next to the MCP door:
227
+
228
+ ```ts
229
+ import { uploadRoute } from '@lupinum/better-convex-agents'
230
+
231
+ // POST /mcp/upload, or the `path` you set in `uploads`.
232
+ http.route(uploadRoute(agents))
233
+ ```
234
+
235
+ ### Take a file in a tool
236
+
237
+ Call `claimUpload` inside a mutation operation, in the same transaction as the
238
+ write that stores the file. Read the target row first, so the row rules decide
239
+ whether this caller may change it.
240
+
241
+ ```ts
242
+ // convex/receipts.ts
243
+ import { claimUpload, fail } from '@lupinum/better-convex-functions'
244
+ import { v } from 'convex/values'
245
+
246
+ import { mutation } from './functions'
247
+
248
+ export const attach = mutation({
249
+ action: 'receipts.attach',
250
+ args: { expenseId: v.id('expenses'), uploadId: v.string() },
251
+ returns: v.null(),
252
+ tool: {
253
+ name: 'attach_receipt',
254
+ description: 'Attach a receipt PDF you sent with request_upload to an expense.',
255
+ },
256
+ handler: async (ctx, { expenseId, uploadId }) => {
257
+ const expense = await ctx.db.get(expenseId)
258
+ if (!expense) fail('NOT_FOUND', 'No expense with this ID.')
259
+ const file = await claimUpload(ctx, uploadId, {
260
+ types: ['application/pdf'],
261
+ maxBytes: 10 * 1024 * 1024,
262
+ })
263
+ await ctx.db.patch(expenseId, { receipt: file.storageId, receiptSha256: file.sha256 })
264
+ return null
265
+ },
266
+ })
267
+ ```
268
+
269
+ `claimUpload` returns `{ storageId, type, size, sha256 }`. The same file sent
270
+ twice has the same `sha256`, so a tool can find a duplicate with an index on
271
+ it. A tool that needs a person's approval claims the file when the person
272
+ approves, as the same agent connection.
273
+
274
+ ### What the agent sees
275
+
276
+ `request_upload` takes `count`, from 1 to 20 files, and returns the URL, the
277
+ tokens and short instructions:
278
+
279
+ ```json
280
+ {
281
+ "url": "https://happy-otter-123.convex.site/mcp/upload",
282
+ "method": "POST",
283
+ "tokens": ["bcu_…"],
284
+ "expiresAt": "2026-10-15T09:30:00.000Z",
285
+ "maxBytes": 10485760,
286
+ "types": ["application/pdf"]
287
+ }
288
+ ```
289
+
290
+ The agent sends each file as the raw request body:
291
+
292
+ ```bash
293
+ curl -X POST --data-binary @receipt.pdf -H "Authorization: Bearer bcu_…" https://happy-otter-123.convex.site/mcp/upload
294
+ ```
295
+
296
+ The route answers `201` with `{ uploadId, type, size, sha256 }`. It answers
297
+ `401` for a token that expired, was used or never existed, `413` for a file
298
+ over `maxBytes`, and `415` for a file of another type. A refused file is not
299
+ stored. Without a valid token the route reads at most 4 MiB of a refused
300
+ body, so a larger file may get a `520` from Convex instead of the `401`.
301
+
302
+ ### Limits and cleanup
303
+
304
+ | Limit | Value | When reached |
305
+ | --- | --- | --- |
306
+ | Links in one `request_upload` call | 1 to 20 | `INVALID_INPUT` |
307
+ | Links and files a connection leaves unclaimed | 100 | `RATE_LIMITED`; use them, or wait until they expire |
308
+ | Time to send a file with a link | 15 minutes | the route answers `401` |
309
+ | Time to claim a stored file | 24 hours | `NOT_FOUND`; `housekeeping` deletes the file |
310
+ | Record of a claimed upload | 30 days | `housekeeping` deletes the record; the file stays |
311
+
312
+ `request_upload` counts against the 60 writes a minute of the connection.
313
+ `housekeeping` deletes expired links and unclaimed files in the same run as
314
+ the other retention work, and account deletion removes a person's links and
315
+ unclaimed files. A claimed file belongs to the row that stores its ID: delete
316
+ it with that row.
317
+
318
+ ### Cost
319
+
320
+ - `request_upload`: reads up to 202 upload rows of the connection by index, writes one row per link and one rate-limit row.
321
+ - The upload route: one query, one storage write and one mutation that writes one row.
322
+ - `claimUpload`: reads and writes one row. It invalidates no query of the application.
323
+
160
324
  ## Connect a host
161
325
 
162
326
  Create one OAuth client for each host with `auth.oauthOperator.createHostClient`,
@@ -23,6 +23,12 @@ export default defineNuxtConfig({
23
23
 
24
24
  Open Nuxt DevTools and select the Better Convex Nuxt panel.
25
25
 
26
+ Nuxt 4 includes `@nuxt/devtools`. Nuxt 5 does not. On Nuxt 5, install it to see the panel:
27
+
28
+ ```bash
29
+ pnpm add -D @nuxt/devtools
30
+ ```
31
+
26
32
  ## Query inspection
27
33
 
28
34
  Use the query list and detail view to inspect:
@@ -37,6 +37,8 @@ Handle errors at the boundary that can make the next decision.
37
37
 
38
38
  A query error stays until its cause changes. Convex runs the query again by itself when the data it read changes or new code is deployed, and the error clears. A failed later page is retried with `loadMore()`.
39
39
 
40
+ A system failure, such as `Function execution timed out`, does not come from the data the query read. It can stay until that data changes or the browser reconnects to Convex, which sends every query again. A query has no retry call: the Convex client keeps one subscription for each query and arguments, shared by every component that uses them, so subscribing again from one component gets the same stored failure. While `error` is set, `data` keeps the last result, so show it with a notice. When there is no data, offer a page reload, for example with `reloadNuxtApp()`. A paginated list can try again with `restart()`, which subscribes its pages under a new pagination id.
41
+
40
42
  ## Structured server errors
41
43
 
42
44
  ```ts
@@ -65,7 +67,7 @@ The codes that Better Convex raises itself include `IDENTITY_CHANGED`, `CANCELLE
65
67
 
66
68
  ## Errors from Nitro routes
67
69
 
68
- A route that rethrows with `toConvexH3Error` returns the serialized error. Revive it in the browser:
70
+ A route that rethrows with `toConvexH3Error` returns the serialized error as an HTTP error (`NuxtError`); on the server, check it with `isNuxtError(error)` from `nuxt/server` and read `error.status`. Revive it in the browser:
69
71
 
70
72
  ```ts
71
73
  import { normalizeConvexError } from '@lupinum/better-convex-nuxt/errors'
@@ -39,6 +39,13 @@ export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
39
39
 
40
40
  Better Convex accepts only `enabled` and `beforeDelete`. The other Better Auth options for `deleteUser` are not available.
41
41
 
42
+ The auth user, its accounts, and up to 64 sessions are deleted in one
43
+ mutation. A user with more sessions, for example a test account that signs in
44
+ often, is deleted too: the other sessions stop working at once, because every
45
+ session check reads the user, and a scheduled function deletes them right
46
+ after, 128 per run. Session `onDelete` triggers do not run for these sessions,
47
+ the same as for sessions that expire.
48
+
42
49
  ### How the person proves it is them
43
50
 
44
51
  - **Without an `email` hook**, the session must be fresh (Better Auth `session.freshAge`, one day by default), or the request must carry the account password. A stale session without the password is refused with `SESSION_EXPIRED`. Ask the person to sign in again, then call `authClient.deleteUser()`.
@@ -240,10 +240,39 @@ that exchanges a cookie for a token outside this path.
240
240
 
241
241
  For Vercel, see [Deploy to Vercel](../../operations/deploy-to-vercel.md#trusted-client-ip-header).
242
242
 
243
+ ### Expired codes and links
244
+
245
+ Better Auth stores every email code, verification link, and OAuth sign-in
246
+ state as a row in the auth component's `verification` table. The component
247
+ deletes each row at its expiry with a scheduled function, `expireVerification`.
248
+ That run also deletes other expired rows, at most 128 in one mutation, and
249
+ schedules itself again until no expired row is left. So rows from an earlier
250
+ version go away after the first new code expires. Better Auth's own cleanup,
251
+ which deleted all expired rows during a sign-in request, is off.
252
+
253
+ Cost: one scheduled function for each code or link. Each run reads one row and
254
+ at most 128 entries of the `expiresAt` index, deletes at most 128 rows, and
255
+ changes only the auth component's `verification` table.
256
+
257
+ ### Email code limits
258
+
259
+ Email-code requests are limited for each client IP and route: three at once,
260
+ then one more every 20 seconds (three per minute over time). Better Convex
261
+ applies the same limit to each email address, counted
262
+ across `/email-otp/send-verification-otp` and the code-based password reset
263
+ routes. So requests from many IP addresses cannot fill one inbox.
264
+ `emailOTP.rateLimit` changes both limits. A blocked request returns `429` with
265
+ an `X-Retry-After` value in seconds. The counter stores a hash of the address,
266
+ not the address. Server code that calls `auth.api` directly is not limited.
267
+
268
+ A person whose limit someone else used up waits up to 20 seconds before a new
269
+ code is sent.
270
+
243
271
  ### Convex token rate limit
244
272
 
245
- The token route `GET /api/auth/convex/token` allows 300 requests per 10
246
- seconds for each client IP. The limit is per IP address, not per user or
273
+ The token route `GET /api/auth/convex/token` allows a burst of 300 requests
274
+ for each client IP, then one more every 33 milliseconds (300 per 10 seconds
275
+ over time). The limit is per IP address, not per user or
247
276
  session. Better Auth stores the counter in the component database, so every
248
277
  server instance shares it. A blocked request returns `429` with an
249
278
  `X-Retry-After` value in seconds.
@@ -44,6 +44,18 @@ export default defineNuxtConfig({
44
44
 
45
45
  The rule `'/**'` also matches `/api/**`, which includes the sign-in routes under `/api/auth`. A cache must never store a response from these routes, because it could serve the session of one user to another visitor. List only your public page paths, not `'/**'`. The `/api/**` rule is a second guard that turns caching off for the auth routes.
46
46
 
47
+ On Nuxt 5, a cached route (`cache`, `swr`, `isr`) ignores the query string unless the rule sets `allowQuery`. On Nuxt 4, the cache key includes the query string. On both, do not cache a page whose HTML depends on a query, such as `?redirect=`.
48
+
49
+ A cache rule (`cache`, `swr`, `isr`) stores the rendered page and replaces the `Vary: Cookie` and `Cache-Control: private, no-store` headers that the module sets on pages for signed-in users. This is true on Nuxt 4 and Nuxt 5. On Nuxt 4, the cached render also runs without the request cookies, so SSR auth renders those pages signed out. On Nuxt 5, a `routeRules` `headers` rule or a server middleware that sets cache headers also overrides the module's headers; on Nuxt 4 the module's headers win over these. Set `convex: { ssrAuth: false }` on every cached route, or remove the cache rule.
50
+
51
+ The module checks the `routeRules` and `nitro.routeRules` of your `nuxt.config` at build time. It does not check server middleware, `defineRouteRules()` in page files, or rules that other modules add. For each of those checked rules that caches a page with SSR auth on, it logs this warning (here for `'/blog/**': { swr: 3600 }`):
52
+
53
+ ```text
54
+ Route rules "/blog/**" cache pages that resolve the Convex session during SSR. A cache rule replaces the `Vary: Cookie` and `Cache-Control: private, no-store` headers the module sets on signed-in pages, and on Nuxt 5 a `headers` rule with cache headers does too. Set `convex: { ssrAuth: false }` on cached routes or drop the cache rule.
55
+ ```
56
+
57
+ Check server middleware, page-level rules and rules from other modules that set cache headers yourself. A `cache-control` header that forbids storing (`no-store`, `private`, `no-cache`, `max-age=0`) is not a cache rule and gets no warning.
58
+
47
59
  ## Turn it off for all routes
48
60
 
49
61
  Set `auth.ssr: false`. A route rule with `convex: { ssrAuth: true }` turns it on again for matching routes.
@@ -47,6 +47,23 @@ definePageMeta({
47
47
 
48
48
  Only local redirect paths are accepted. Protocol-relative paths, backslashes, control characters, and unsafe decoded paths are rejected. An unsafe page-specific `redirectTo` falls back to `convex.auth.redirectTo`; the page stays protected.
49
49
 
50
+ ## When auth is temporarily unavailable
51
+
52
+ A 429, a 5xx, a timeout or a network error from the auth backend says nothing about the person. The middleware does not redirect then: it renders the protected page with `useConvexAuth().status` set to `'error'` (or still `'pending'` while the browser waits out the failure), and `error.message` is "Authentication is temporarily unavailable". The browser keeps retrying and recovers on its own. Show that state instead of a signed-out view:
53
+
54
+ ```vue
55
+ <script setup lang="ts">
56
+ const { status } = useConvexAuth()
57
+ </script>
58
+
59
+ <template>
60
+ <p v-if="status === 'error'">Reconnecting…</p>
61
+ <slot v-else />
62
+ </template>
63
+ ```
64
+
65
+ Convex still refuses data the person may not read, and queries with `auth: 'required'` stay idle until the identity is known. Any other failure still redirects.
66
+
50
67
  ## Keep signed-in users off guest pages
51
68
 
52
69
  Mark a sign-in or sign-up page as guest-only:
@@ -113,6 +113,8 @@ await navigateTo('/')
113
113
 
114
114
  Your application decides where to navigate. The module orders the session operations, clears the previous user's query data, and replaces the Convex client.
115
115
 
116
+ Do not call `clearNuxtState()` without keys during sign-out. On Nuxt 5 it resets the module's `convex:*` state to its initial value. The auth state then shows as pending, nothing loads it again, and protected routes wait until their timeout and then treat the visitor as signed out. Pass the keys of your own state, for example `clearNuxtState(['cart'])`.
117
+
116
118
  ## Wait for the auth state
117
119
 
118
120
  Queries already wait for auth. Use `ready()` only when other code must wait until the first auth state is known:
@@ -69,7 +69,11 @@ a public endpoint that accepts arbitrary recipients or links.
69
69
  | `organization-invitation` | The `organization` capability invites a member | `invitationId`, `role`, `organization`, `inviter` |
70
70
  | `delete-account` | `deleteUser` is enabled and a person deletes | `url`, `token`, `user` |
71
71
 
72
- `purpose` is `sign-in`, `email-verification`, or `forget-password`. `user` and `inviter` contain `id`, `email`, and `name`. An
72
+ `purpose` is `sign-in`, `email-verification`, or `forget-password`. A
73
+ `forget-password` code is sent only when `emailAndPassword.passwordReset` is
74
+ `true`, and an `email-verification` code only to an address that is not
75
+ verified yet. Other requests still answer with success and send no mail, so
76
+ the answer does not show whether an account exists. `user` and `inviter` contain `id`, `email`, and `name`. An
73
77
  invitation has no link. Build it from your application origin and
74
78
  `invitationId`, for example with `requireAuthOrigin('SITE_URL')`.
75
79
 
@@ -189,6 +189,10 @@ When the signed-in user changes after the file was stored but before `complete`
189
189
 
190
190
  ## Attach the file safely
191
191
 
192
+ <note>
193
+ This recipe is for files a person sends from the browser. For a file an agent sends over MCP, use `claimUpload` from `@lupinum/better-convex-functions`: see [Files from agents](../agents/mcp-door.md#files-from-agents). The helper below has the same name but takes an owner ID and a storage ID.
194
+ </note>
195
+
192
196
  A storage ID from the browser is only a claim. The upload URL does not tie a file to a user or a document. Before a mutation uses a storage ID, it must check four things:
193
197
 
194
198
  1. The caller is signed in.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  title: "Internal operations"
3
- description: "Run follow-up work as the same caller, call an outside service from an action, and run jobs from a cron."
3
+ description: "Run follow-up work as the same caller, call an outside service from an action, start outside work from the browser, and run jobs from a cron."
4
4
  url: "https://better-convex.lupinum.com/docs/build/functions/internal-operations"
5
5
  route: "/docs/build/functions/internal-operations"
6
6
  locale: "en"
@@ -11,7 +11,7 @@ source: "ginko-content"
11
11
 
12
12
  # Internal operations
13
13
 
14
- > Run follow-up work as the same caller, call an outside service from an action, and run jobs from a cron.
14
+ > Run follow-up work as the same caller, call an outside service from an action, start outside work from the browser, and run jobs from a cron.
15
15
 
16
16
  An operation often starts more work: it schedules an action that calls an
17
17
  outside service, and that action reads and writes again. Build those
@@ -129,14 +129,90 @@ only through `ctx.runQuery` and `ctx.runMutation` of internal operations.
129
129
  `ctx.actor` is who it acts for, as the caller passed it. It is checked in each
130
130
  of those calls, not when the action starts.
131
131
 
132
+ ## Public actions
133
+
134
+ Some work starts in the browser and runs outside the database: render a PDF,
135
+ read a file that a person uploaded, import a CSV file, or call a service while
136
+ the person waits. Build it with `action`. Before the handler runs, the call
137
+ checks the caller, the policy and the tenant that the arguments name, as a
138
+ public mutation does. It also takes the action's
139
+ [limit](./limits-and-audit.md) token.
140
+
141
+ A Convex action has no database, so the check runs in an internal mutation of
142
+ its own: `authorizeAction`. Export it from `convex/functions.ts`, and give its
143
+ reference to `fns.action` once, as the `convex/functions.ts` file in
144
+ [Row rules](./row-rules.md) does:
145
+
146
+ ```ts
147
+ export const { authorizeAction } = fns
148
+ export const action = fns.action(internal.functions.authorizeAction)
149
+ ```
150
+
151
+ Then build each public action with `action`. This one makes the summary from
152
+ the first example while the person waits, and reuses its internal operations:
153
+
154
+ ```ts [convex/summaryNow.ts]
155
+ import { v } from 'convex/values'
156
+
157
+ import { internal } from './_generated/api'
158
+ import { action } from './functions'
159
+
160
+ /** The summary of a project, made now. The summary service runs outside the database. */
161
+ export const summarize = action({
162
+ action: 'projects.summarize',
163
+ args: { projectId: v.id('projects') },
164
+ returns: v.string(),
165
+ handler: async (ctx, { projectId }) => {
166
+ const { name } = await ctx.runQuery(internal.summaryWork.load, { projectId })
167
+ const response = await fetch('https://summaries.example.com/v1/summarize', {
168
+ method: 'POST',
169
+ headers: { 'content-type': 'application/json' },
170
+ body: JSON.stringify({ text: name }),
171
+ })
172
+ if (!response.ok) throw new Error(`The summary service answered ${response.status}.`)
173
+ const { summary } = (await response.json()) as { summary: string }
174
+ await ctx.runMutation(internal.summaryWork.save, { projectId, summary })
175
+ return summary
176
+ },
177
+ })
178
+ ```
179
+
180
+ What the check does, and what it does not do:
181
+
182
+ - A person whose role does not allow the action gets `FORBIDDEN`. A signed-out
183
+ visitor gets `NOT_SIGNED_IN`, unless the action is in `public`. The handler
184
+ does not run.
185
+ - The role comes from the tenant that an ID in the arguments names. A call
186
+ that names no tenant needs the role outside any tenant
187
+ (`roleOf(ctx, user, null)`), unless its action is public.
188
+ - The arguments name IDs from one place, as in a mutation without
189
+ `crossTenant`. An action has no `crossTenant`.
190
+ - `ctx.actor` is the caller that the check found. The handler has no `ctx.db`:
191
+ `ctx.runQuery`, `ctx.runMutation`, `ctx.runAction` and `ctx.scheduler` reach
192
+ internal operations as that caller, and each one checks it again.
193
+ - The check takes the action's token. A mutation that the handler runs with
194
+ `ctx.runMutation` takes no second token from the same bucket. A mutation with
195
+ another bucket (another action, or another tenant) takes its own token. The
196
+ token stays spent when the handler fails later: an action has no transaction.
197
+ - The check writes no audit row. Each audited internal mutation that the
198
+ handler runs writes its own row.
199
+ - A file ID (`v.id('_storage')`) names no tenant, and `ctx.storage` reads any
200
+ file. Never read a file by an ID from the arguments. Take the ID from a row
201
+ that an internal query of the action may read, so the row rules decide:
202
+ `const { fileId } = await ctx.runQuery(internal.imports.upload, { uploadId })`.
203
+ - An action is not a tool. Agents reach your application through tools only.
204
+ If an agent needs the same work, write a mutation with a `tool` field that
205
+ schedules an internal action.
206
+
132
207
  ## Raw functions cannot be reached
133
208
 
134
209
  An operation cannot call a function built with Convex's own builders. The
135
210
  call fails, and nothing that the call did is kept, even when the handler
136
211
  catches the error.
137
212
 
138
- An internal action has no transaction. When it reaches a raw function, the
139
- raw function's writes are already committed; the action fails loudly. The
213
+ An internal or public action has no transaction. When it reaches a raw
214
+ function, the raw function's writes are already committed; the action fails
215
+ loudly. The
140
216
  [no-bypass test](./testing.md#no-raw-functions) is what
141
217
  prevents this: it fails while a raw internal function exists.
142
218
 
@@ -64,9 +64,13 @@ What counts:
64
64
  - The policy decides first. A call it denies (`NOT_SIGNED_IN`, `FORBIDDEN`,
65
65
  `NOT_FOUND`) never takes a token.
66
66
  - The token is taken in the transaction of the call, before the handler. A
67
- call that fails gives its token back, so a call that fails does not count.
68
- - Every mutation built with `fns` is limited, public or internal. An internal
69
- mutation that is scheduled, or run from an action, takes its own token.
67
+ mutation that fails gives its token back, so it does not count. A public
68
+ action takes its token in its check (`authorizeAction`), before its handler
69
+ runs; when the handler fails, the token stays spent: an action has no
70
+ transaction.
71
+ - Every mutation built with `fns` is limited, public or internal, and so is
72
+ every public action. An internal mutation that is scheduled, or run from an
73
+ internal action, takes its own token.
70
74
  - A mutation run with `ctx.runMutation` takes no token for an action that a
71
75
  call above it already took one for.
72
76
  - Jobs and other system calls are never limited.
@@ -77,13 +81,19 @@ What counts:
77
81
  - Wrong definitions throw when the policy is defined: an action that is not in
78
82
  `actions`, `max` below 1 or not whole, an unknown `every` or `per`.
79
83
 
80
- ### Actions
84
+ ### Convex actions
81
85
 
82
- Limits apply to mutations only. A Convex action has no database of its own,
83
- so it cannot take a token. Limit the action of the internal mutation it runs
84
- with `ctx.runMutation`: that mutation takes the token, whoever calls it. A
85
- `limits` entry for an action that no mutation uses (a query only) throws when
86
- the query is defined: "is limited, but no mutation uses it".
86
+ A public action built with `action` takes its token in its check, before the
87
+ handler runs. A mutation that the handler runs with `ctx.runMutation` takes no
88
+ second token from the same bucket. An action has no transaction, so a call
89
+ that fails after the check keeps its token spent.
90
+
91
+ An internal action has no check of its own. Limit the action of the internal
92
+ mutation it runs with `ctx.runMutation`: that mutation takes the token,
93
+ whoever calls it.
94
+
95
+ A query cannot take a token. A `limits` entry for an action that only a query
96
+ uses throws when the query is defined: "is limited, but no mutation uses it".
87
97
 
88
98
  ### Storage
89
99
 
@@ -84,12 +84,44 @@ key of `roles` allows nothing, also names such as `toString` or `__proto__`.
84
84
  `roleOf` and `user` get a context that only reads: they decide, they do not
85
85
  change data.
86
86
 
87
+ A call whose input names no tenant gets its role from `roleOf(ctx, user, null)`:
88
+ the role a person has outside any tenant. `null` refuses the call, unless its
89
+ action is public. What every signed-in person may do (create an organization,
90
+ list their own organizations) is a role too, for example `signedIn`:
91
+
92
+ ```ts
93
+ roles: {
94
+ signedIn: ['organizations.create', 'organizations.list'],
95
+ owner: ['*'],
96
+ member: ['projects.create', 'projects.rename'],
97
+ },
98
+ ```
99
+
100
+ ```ts
101
+ roleOf: async (ctx, user, tenant) => {
102
+ if (tenant === null) return 'signedIn'
103
+ // the membership lookup for a tenant
104
+ },
105
+ ```
106
+
107
+ An application with one workspace and no tenant tables returns the member's role
108
+ for `null`, and the library checks it on every call, so no handler has to. Answer
109
+ `null` for a tenant you do not handle, so a tenant table added later cannot
110
+ inherit the workspace role:
111
+
112
+ ```ts
113
+ roleOf: async (ctx, user, tenant) => (tenant === null ? user.role : null),
114
+ ```
115
+
87
116
  ## How one call is decided
88
117
 
89
118
  A call is allowed when every layer allows it:
90
119
 
91
- 1. **Role.** The caller's role in the call's tenant allows the action. A
92
- public action skips this layer.
120
+ 1. **Role.** The caller's role where the call acts allows the action: the
121
+ role in the tenant the input names, or, when it names none, the role outside
122
+ any tenant (`roleOf(ctx, user, null)`). No role refuses the call. A public
123
+ action skips this layer. The row rules then check every row the call
124
+ touches.
93
125
  2. **Scope** (agents only). One of the scopes the person granted includes the
94
126
  action.
95
127
  3. **Agent rule** (agents only). `allow` runs the call, `approve` holds it for