@lupinum/better-convex-vue 1.0.2 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/AGENTS.md +6 -3
- package/dist/agent/pages/docs/build/application-behavior/error-handling.md +40 -1
- package/dist/agent/pages/docs/build/authentication/account-deletion.md +73 -0
- package/dist/agent/pages/docs/build/authentication/backend-authorization.md +6 -1
- package/dist/agent/pages/docs/build/authentication/better-auth-setup.md +3 -1
- package/dist/agent/pages/docs/build/authentication/sign-in-and-sign-out.md +3 -0
- package/dist/agent/pages/docs/build/authentication/transactional-email.md +45 -10
- package/dist/agent/pages/docs/build/files/private-downloads.md +126 -0
- package/dist/agent/pages/docs/build/files/storage-urls.md +8 -3
- package/dist/agent/pages/docs/build/files/upload-files.md +2 -2
- package/dist/agent/pages/docs/build/functions/limits-and-audit.md +142 -4
- package/dist/agent/pages/docs/build/functions/testing.md +24 -0
- package/dist/agent/pages/docs/build/queries/loading-and-stale-data.md +1 -1
- package/dist/agent/pages/docs/build/queries/pagination.md +2 -2
- package/dist/agent/pages/docs/build/queries/reactive-arguments.md +46 -0
- package/dist/agent/pages/docs/build/server/server-convex.md +16 -1
- package/dist/agent/pages/docs/build/write-data/concurrent-operations.md +1 -1
- package/dist/agent/pages/docs/build/write-data/forms.md +1 -1
- package/dist/agent/pages/docs/build/write-data/multi-step-operations.md +1 -1
- package/dist/agent/pages/docs/build/write-data/optimistic-updates.md +1 -1
- package/dist/agent/pages/docs/get-started/add-authentication.md +1 -1
- package/dist/agent/pages/docs/operations/before-launch.md +1 -1
- package/dist/agent/pages/docs/operations/log-streams.md +128 -0
- package/dist/agent/pages/docs/recipes/dynamic-query-list.md +1 -1
- package/dist/agent/pages/docs/recipes/error-messages.md +1 -1
- package/dist/agent/pages/docs/recipes/guest-users.md +67 -15
- package/dist/agent/pages/docs/recipes/multiple-file-uploads.md +1 -1
- package/dist/agent/pages/docs/recipes/optimistic-todo-list.md +1 -1
- package/dist/agent/pages/docs/recipes/realtime-feed.md +1 -1
- package/dist/agent/pages/docs/recipes/sign-in-link.md +129 -0
- package/dist/agent/pages/docs/reference/api-surface.md +11 -0
- package/dist/agent/pages/docs/reference/error-types.md +12 -2
- package/dist/agent/pages/docs/reference/operation-error-codes.md +15 -1
- package/dist/agent/pages/docs/reference/package-exports.md +3 -2
- package/dist/agent/pages/docs/reference/server-api.md +5 -1
- package/dist/errors.d.mts +31 -3
- package/dist/errors.d.ts +31 -3
- package/dist/errors.mjs +59 -7
- package/package.json +1 -1
package/dist/agent/AGENTS.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
# @lupinum/better-convex-vue 1.0
|
|
1
|
+
# @lupinum/better-convex-vue 1.1.0 documentation
|
|
2
2
|
|
|
3
|
-
These pages describe the installed version 1.0.
|
|
3
|
+
These pages describe the installed version 1.1.0. 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
|
|
@@ -96,6 +96,7 @@ website and over knowledge of earlier versions: the API changed during the 1.0 b
|
|
|
96
96
|
- [Upload files](./pages/docs/build/files/upload-files.md)
|
|
97
97
|
- [Storage URLs](./pages/docs/build/files/storage-urls.md)
|
|
98
98
|
- [File validation and deletion](./pages/docs/build/files/validation-and-deletion.md)
|
|
99
|
+
- [Private downloads](./pages/docs/build/files/private-downloads.md)
|
|
99
100
|
- [Connection state](./pages/docs/build/application-behavior/connection-state.md)
|
|
100
101
|
- [Error handling](./pages/docs/build/application-behavior/error-handling.md)
|
|
101
102
|
- [Logging](./pages/docs/build/application-behavior/logging.md)
|
|
@@ -116,7 +117,7 @@ website and over knowledge of earlier versions: the API changed during the 1.0 b
|
|
|
116
117
|
- [Test your app](./pages/docs/build/functions/testing.md)
|
|
117
118
|
- [Cost](./pages/docs/build/functions/cost.md)
|
|
118
119
|
- [Threat model](./pages/docs/build/functions/threat-model.md)
|
|
119
|
-
- [Rate limits and
|
|
120
|
+
- [Rate limits, audit log and call events](./pages/docs/build/functions/limits-and-audit.md)
|
|
120
121
|
|
|
121
122
|
### Recipes
|
|
122
123
|
|
|
@@ -134,6 +135,7 @@ website and over knowledge of earlier versions: the API changed during the 1.0 b
|
|
|
134
135
|
- [Error messages](./pages/docs/recipes/error-messages.md)
|
|
135
136
|
- [Several file uploads](./pages/docs/recipes/multiple-file-uploads.md)
|
|
136
137
|
- [Guest users](./pages/docs/recipes/guest-users.md)
|
|
138
|
+
- [Sign-in link](./pages/docs/recipes/sign-in-link.md)
|
|
137
139
|
|
|
138
140
|
### Concepts
|
|
139
141
|
|
|
@@ -157,6 +159,7 @@ website and over knowledge of earlier versions: the API changed during the 1.0 b
|
|
|
157
159
|
- [Security model](./pages/docs/operations/security-model.md)
|
|
158
160
|
- [Upgrade to 1.0](./pages/docs/operations/upgrade-to-1-0.md)
|
|
159
161
|
- [Before your app goes live](./pages/docs/operations/before-launch.md)
|
|
162
|
+
- [Log streams and PostHog](./pages/docs/operations/log-streams.md)
|
|
160
163
|
|
|
161
164
|
### Reference
|
|
162
165
|
|
|
@@ -61,6 +61,45 @@ async function archive() {
|
|
|
61
61
|
|
|
62
62
|
Use `code`, not message substrings, for decisions. A `server` error's `code` is the `data.code` of the `ConvexError`, and its `message` is the text the Convex function wrote in `data.message`. Show that message to the user only when the backend writes user-facing text.
|
|
63
63
|
|
|
64
|
+
## Show why and how to fix it
|
|
65
|
+
|
|
66
|
+
A Convex function can tell the user why it refused and what they can do. With `@lupinum/better-convex-functions`, pass `why` and `fix` to `fail`:
|
|
67
|
+
|
|
68
|
+
```ts [convex/documents.ts]
|
|
69
|
+
fail('INVALID_INPUT', 'The invoice could not be sent.', {
|
|
70
|
+
why: 'The client has no email address.',
|
|
71
|
+
fix: 'Add an email address in the client settings.',
|
|
72
|
+
})
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Without the functions package, put them in the error data: `throw new ConvexError({ code, message, why, fix })`.
|
|
76
|
+
|
|
77
|
+
The `ConvexCallError` then has `why` and `fix`:
|
|
78
|
+
|
|
79
|
+
```vue
|
|
80
|
+
<section v-if="error" role="alert">
|
|
81
|
+
<p>{{ error.message }}</p>
|
|
82
|
+
<p v-if="error.why">{{ error.why }}</p>
|
|
83
|
+
<p v-if="error.fix">{{ error.fix }}</p>
|
|
84
|
+
</section>
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Write `why` and `fix` for the user. Do not build them from internal state, IDs, or the error text of another service. `NOT_FOUND` and `FAILED` take no help, and `fail` rejects it at compile time: `NOT_FOUND` must read like a missing row, and `FAILED` keeps its detail in the log. Agents that call the function through the MCP door receive the same `why` and `fix`. They get help only with the library's codes: for a code of your own, the MCP door answers `FAILED` without it. When work that a person approved fails, only its `code` and `message` are kept: the person who approved it and the agent that checks its request see no `why` or `fix`.
|
|
88
|
+
|
|
89
|
+
`why` and `fix` are server text in one language. When your app shows its own text for each `code`, for example in another language, keep that text for people. Then `why` and `fix` are for agents, and for a `code` that has no text of its own.
|
|
90
|
+
|
|
91
|
+
## Quote the request ID
|
|
92
|
+
|
|
93
|
+
When a Convex function fails, `error.requestId` holds the Convex request ID of the call. The Convex logs and log streams record the same ID. Show it with an unexpected failure, so that the user can quote it:
|
|
94
|
+
|
|
95
|
+
```vue
|
|
96
|
+
<p v-if="error?.requestId">Reference: {{ error.requestId }}</p>
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
To find the call, search for the ID in the logs of your Convex dashboard or in your log stream. On a local backend, `npx convex logs --jsonl` shows the `requestId` of each call; the log lines that `convex dev` prints do not. An unexpected failure (kind `unknown`) keeps its request ID, but not its text.
|
|
100
|
+
|
|
101
|
+
Better Convex reads the ID from the error text of Convex, which is not a stable Convex contract. When Convex changes that text, `requestId` is `undefined`.
|
|
102
|
+
|
|
64
103
|
## Library error codes
|
|
65
104
|
|
|
66
105
|
The codes that Better Convex raises itself include `IDENTITY_CHANGED`, `CANCELLED`, `FILE_TOO_LARGE`, `FILE_TYPE_NOT_ALLOWED`, `UPLOAD_IN_PROGRESS`, `SUBMIT_IN_PROGRESS`, `UNAUTHENTICATED`, `CLIENT_UNAVAILABLE`, `NETWORK_ERROR`, and `TIMEOUT`. The type `ConvexCallErrorCode` lists every code. Ignore `CANCELLED` when your own `cancel()` or `reset()` caused it. Do not retry `IDENTITY_CHANGED` automatically. See [error types](../../reference/error-types.md#convexcallerrorcode).
|
|
@@ -88,7 +127,7 @@ Vue/Nuxt error boundaries are appropriate for render failures or page-level inab
|
|
|
88
127
|
|
|
89
128
|
## Logging
|
|
90
129
|
|
|
91
|
-
Log the category, `functionName`, and safe correlation context. Do not log tokens, cookies, auth headers,
|
|
130
|
+
Log the category, `functionName`, `requestId`, and safe correlation context. Do not log tokens, cookies, auth headers,
|
|
92
131
|
raw upload bytes, or upstream error objects. `ConvexCallError` does not retain the raw upstream cause.
|
|
93
132
|
|
|
94
133
|
## Retry safety
|
|
@@ -131,3 +131,76 @@ Each step reads at most 100 rows or 4 MiB, deletes or patches them, and schedule
|
|
|
131
131
|
Erasure removes rows that your own tables hold. It does not reach files in storage, backups, logs, or other services. Remove those in `beforeDelete`, or in your own scheduled function.
|
|
132
132
|
|
|
133
133
|
Test it once with real data: create a person with rows in each mapped table, delete the account, run the scheduled steps, and check what is left. The starter's `convex/account.test.ts` shows how.
|
|
134
|
+
|
|
135
|
+
## Delete another user from a Convex function
|
|
136
|
+
|
|
137
|
+
An admin removes a member, or you act on an erasure request that reached you by
|
|
138
|
+
email. Call `auth.deleteUser(ctx, userId)` from an internal mutation, after your
|
|
139
|
+
own check of who may delete whom.
|
|
140
|
+
|
|
141
|
+
```ts [convex/members.ts]
|
|
142
|
+
import { ConvexError, v } from 'convex/values'
|
|
143
|
+
|
|
144
|
+
import { internal } from './_generated/api'
|
|
145
|
+
import { internalMutation, mutation } from './_generated/server'
|
|
146
|
+
import { auth } from './auth'
|
|
147
|
+
|
|
148
|
+
export const remove = mutation({
|
|
149
|
+
args: { authUserId: v.string() },
|
|
150
|
+
handler: async (ctx, args): Promise<null> => {
|
|
151
|
+
const caller = await auth.requireUser(ctx)
|
|
152
|
+
const me = await ctx.db
|
|
153
|
+
.query('users')
|
|
154
|
+
.withIndex('by_auth_id', (q) => q.eq('authId', caller.id))
|
|
155
|
+
.unique()
|
|
156
|
+
if (me?.role !== 'admin') throw new ConvexError({ code: 'FORBIDDEN' })
|
|
157
|
+
await ctx.runMutation(internal.members.deleteAuthUser, { authUserId: args.authUserId })
|
|
158
|
+
return null
|
|
159
|
+
},
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
export const deleteAuthUser = internalMutation({
|
|
163
|
+
args: { authUserId: v.string() },
|
|
164
|
+
handler: async (ctx, args): Promise<null> => {
|
|
165
|
+
await auth.deleteUser(ctx, args.authUserId)
|
|
166
|
+
return null
|
|
167
|
+
},
|
|
168
|
+
})
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
The `users` table has a `role` field and the index `by_auth_id` on `authId`.
|
|
172
|
+
|
|
173
|
+
`auth.deleteUser` checks no permission. It deletes whichever user ID it gets, so
|
|
174
|
+
never pass an ID from the browser to it without a check like the one in `remove`.
|
|
175
|
+
|
|
176
|
+
It is the same deletion that `authClient.deleteUser()` does. The user's
|
|
177
|
+
sessions stop working at once. Better Auth then deletes the sessions, the
|
|
178
|
+
linked accounts and the auth user. Your `onDelete` triggers run for each of
|
|
179
|
+
these rows, so the user projection deletes the app user row and runs your
|
|
180
|
+
`erase` hook. The session limit above applies here too: sessions after the
|
|
181
|
+
first 64 are deleted later, without `onDelete` triggers. A user ID that does not
|
|
182
|
+
exist is not an error.
|
|
183
|
+
|
|
184
|
+
These steps belong to the person's own delete request and do not run here:
|
|
185
|
+
|
|
186
|
+
- `deleteUser.beforeDelete`. Do the same checks before you call
|
|
187
|
+
`deleteAuthUser`.
|
|
188
|
+
- The fresh session or password check, and the `delete-account` email.
|
|
189
|
+
- The `deleteUser.enabled` switch. `auth.deleteUser` works without it.
|
|
190
|
+
|
|
191
|
+
In a mutation, the deletion is one transaction. From an action it also works,
|
|
192
|
+
but each step is its own transaction; if one fails, call `auth.deleteUser`
|
|
193
|
+
again to finish. A query cannot delete: the call throws
|
|
194
|
+
`AUTH_DELETE_USER_REQUIRES_WRITABLE_CONTEXT`.
|
|
195
|
+
|
|
196
|
+
Cost: it reads the user, its sessions and its accounts in the auth component,
|
|
197
|
+
updates the user once so that every session stops working, and deletes the
|
|
198
|
+
accounts, up to 64 sessions and the user. Each deleted row runs your `onDelete`
|
|
199
|
+
trigger in the same transaction. Queries that read these auth rows for the user,
|
|
200
|
+
such as `getUser` in that person's open tabs, and queries that read the rows
|
|
201
|
+
your triggers change, update.
|
|
202
|
+
|
|
203
|
+
Do not call the component mutation `components.betterAuth.adapter.deleteOne`
|
|
204
|
+
for the user. It deletes the sessions and accounts too, but it does not run your
|
|
205
|
+
`onDelete` triggers. The app user row and the data that `erase` removes stay
|
|
206
|
+
behind.
|
|
@@ -38,7 +38,9 @@ session.
|
|
|
38
38
|
## Authenticate an HTTP action
|
|
39
39
|
|
|
40
40
|
An HTTP action receives the browser's session cookie, not a Convex token. Wrap
|
|
41
|
-
it in `auth.sessionHttpAction` instead of reading the cookie yourself
|
|
41
|
+
it in `auth.sessionHttpAction` instead of reading the cookie yourself. To send
|
|
42
|
+
files, use a [private download route](../files/private-downloads.md)
|
|
43
|
+
instead:
|
|
42
44
|
|
|
43
45
|
```ts [convex/http.ts]
|
|
44
46
|
http.route({
|
|
@@ -59,6 +61,9 @@ gets `401` `UNAUTHENTICATED` or `403` `FORBIDDEN` and never reaches the
|
|
|
59
61
|
handler. Mount the route under `/api/auth/` so browser calls pass through the
|
|
60
62
|
auth proxy.
|
|
61
63
|
|
|
64
|
+
The auth proxy reads the whole response into memory and refuses a response
|
|
65
|
+
larger than 1 MiB. Do not send files through `sessionHttpAction`.
|
|
66
|
+
|
|
62
67
|
## Check the resource
|
|
63
68
|
|
|
64
69
|
```ts [convex/projects.ts]
|
|
@@ -87,7 +87,9 @@ address. See
|
|
|
87
87
|
[Transactional auth email](./transactional-email.md#add-the-email-hook)
|
|
88
88
|
for a complete one. `internal.members.findInvite` is your own internal query. The callback
|
|
89
89
|
receives a read-only copy of the new user: `email`, `emailVerified`, `name`,
|
|
90
|
-
and `
|
|
90
|
+
`image`, and `isAnonymous`. `isAnonymous` is `true` for a guest from
|
|
91
|
+
[`experimental.anonymous`](../../recipes/guest-users.md) and `false` for every
|
|
92
|
+
other new user. It has no `id` yet, because Better Auth assigns it after the
|
|
91
93
|
callback. If you return an `id`, it must be a value that no Better Auth user
|
|
92
94
|
has; do not use it to attach a sign-up to an existing user.
|
|
93
95
|
|
|
@@ -102,6 +102,9 @@ A code proves the address, so a person who signs in this way replaces any
|
|
|
102
102
|
password or session an earlier sign-up left on that address. Codes are stored
|
|
103
103
|
hashed.
|
|
104
104
|
|
|
105
|
+
To let people sign in with one tap from the email, put the code in a link. See
|
|
106
|
+
[Sign-in link](../../recipes/sign-in-link.md).
|
|
107
|
+
|
|
105
108
|
## Sign-out
|
|
106
109
|
|
|
107
110
|
```ts
|
|
@@ -90,18 +90,32 @@ Write the `verify-email` message so it says: "If you did not create an account,
|
|
|
90
90
|
ignore this email." See
|
|
91
91
|
[Password sign-in and access by email](./sign-in-and-sign-out.md#password-sign-in-and-access-by-email).
|
|
92
92
|
|
|
93
|
-
###
|
|
93
|
+
### Local development and the dev outbox
|
|
94
94
|
|
|
95
|
-
|
|
95
|
+
On a loopback `SITE_URL` (`http://localhost:3000`, `http://127.0.0.1:3000`)
|
|
96
|
+
without `siteOrigins`, the dev outbox writes each code and link to the Convex
|
|
97
|
+
function log, as
|
|
98
|
+
`[better-convex-nuxt dev outbox] email-otp to you@example.com: code 123456`.
|
|
99
|
+
Read it with `pnpm exec better-convex-nuxt convex logs`. `NODE_ENV` plays no part.
|
|
96
100
|
|
|
97
|
-
- **
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
101
|
+
- **Without the `email` option**, the log is the only delivery, so a new
|
|
102
|
+
project can sign in before it has a mail provider.
|
|
103
|
+
- **With the `email` option**, the library writes the log line first and then
|
|
104
|
+
calls your hook. You can test your templates and queue locally and still read
|
|
105
|
+
the code when the hook has no provider key.
|
|
106
|
+
|
|
107
|
+
On any other `SITE_URL`, the dev outbox never writes to the log, with or
|
|
108
|
+
without the hook. A cloud development deployment whose `SITE_URL` is
|
|
109
|
+
`http://localhost:3000` counts as local: everyone who can read its logs can
|
|
110
|
+
read the codes.
|
|
111
|
+
|
|
112
|
+
### No `email` option on a deployment
|
|
113
|
+
|
|
114
|
+
On a `SITE_URL` that is not loopback, `createBetterConvexAuth` throws when the
|
|
115
|
+
deployment must send mail (`emailOTP`, password verification or reset,
|
|
116
|
+
organization invitations) and has no `email` option. The deploy fails and the
|
|
117
|
+
previous version keeps running. Add the `email` option, or leave those features
|
|
118
|
+
out.
|
|
105
119
|
|
|
106
120
|
## Submit durable work
|
|
107
121
|
|
|
@@ -124,6 +138,27 @@ promise. Auth token creation and a later submission can be separate
|
|
|
124
138
|
transactions; test submission failure and safe user retries in the
|
|
125
139
|
application. Never include the credential-bearing message in an error.
|
|
126
140
|
|
|
141
|
+
### Codes and links wait in your queue
|
|
142
|
+
|
|
143
|
+
Until your queue sends the email, the code or link is stored in plain text.
|
|
144
|
+
Store it in a row of your own table, schedule the sending action with only the
|
|
145
|
+
row ID, and delete the row after the email is sent. Do not pass the code in the
|
|
146
|
+
arguments of a scheduled function: they stay in the `_scheduled_functions`
|
|
147
|
+
system table after the function runs, and people with access to the Convex
|
|
148
|
+
dashboard can read them.
|
|
149
|
+
|
|
150
|
+
These rules limit what a stored code can do:
|
|
151
|
+
|
|
152
|
+
- Better Auth stores the code hashed in the auth tables. This is the library
|
|
153
|
+
default (`storeOTP: 'hashed'`); another `emailOTP.storeOTP` value changes it.
|
|
154
|
+
With the default, only your queue holds the plain code.
|
|
155
|
+
- The code expires after `emailOTP.expiresIn` seconds, 300 by default. After
|
|
156
|
+
that, a stored code is worthless. Keep this value short.
|
|
157
|
+
- The code stops working after `emailOTP.allowedAttempts` wrong codes, 3 by
|
|
158
|
+
default.
|
|
159
|
+
|
|
160
|
+
A reset or verification link gives access in the same way until it expires.
|
|
161
|
+
|
|
127
162
|
## Configure the capabilities
|
|
128
163
|
|
|
129
164
|
The library sets the email callbacks of Better Auth. These options are
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: "Private downloads"
|
|
3
|
+
description: "Serve a private file from your own origin and check access on every request."
|
|
4
|
+
url: "https://better-convex.lupinum.com/docs/build/files/private-downloads"
|
|
5
|
+
route: "/docs/build/files/private-downloads"
|
|
6
|
+
locale: "en"
|
|
7
|
+
section: "Documentation"
|
|
8
|
+
collection: "docs"
|
|
9
|
+
source: "ginko-content"
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
# Private downloads
|
|
13
|
+
|
|
14
|
+
> Serve a private file from your own origin and check access on every request.
|
|
15
|
+
|
|
16
|
+
A [storage URL](./storage-urls.md) works for anyone who has it, and
|
|
17
|
+
it does not expire. Use a private download route when a file must stay private
|
|
18
|
+
after the link is shared, or when access can end: a member leaves, a document is
|
|
19
|
+
withdrawn, a session is revoked.
|
|
20
|
+
|
|
21
|
+
The route has two parts:
|
|
22
|
+
|
|
23
|
+
1. A Convex HTTP action that checks the caller and the document, then sends the
|
|
24
|
+
file.
|
|
25
|
+
2. A Nuxt server route on your own origin that calls the HTTP action with the
|
|
26
|
+
caller's Convex session token.
|
|
27
|
+
|
|
28
|
+
The browser never sees a storage URL, and `<img src>` and links work with the
|
|
29
|
+
session cookie.
|
|
30
|
+
|
|
31
|
+
## Check access in the HTTP action
|
|
32
|
+
|
|
33
|
+
```ts [convex/http.ts]
|
|
34
|
+
import { httpRouter } from 'convex/server'
|
|
35
|
+
|
|
36
|
+
import { internal } from './_generated/api'
|
|
37
|
+
import { httpAction } from './_generated/server'
|
|
38
|
+
import { auth } from './auth'
|
|
39
|
+
|
|
40
|
+
const http = httpRouter()
|
|
41
|
+
auth.registerRoutes(http)
|
|
42
|
+
|
|
43
|
+
const noStore = { 'cache-control': 'private, no-store' }
|
|
44
|
+
|
|
45
|
+
http.route({
|
|
46
|
+
pathPrefix: '/files/',
|
|
47
|
+
method: 'GET',
|
|
48
|
+
handler: httpAction(async (ctx, request) => {
|
|
49
|
+
const user = await auth.getUser(ctx)
|
|
50
|
+
if (!user) return new Response(null, { status: 401, headers: noStore })
|
|
51
|
+
const id = new URL(request.url).pathname.slice('/files/'.length)
|
|
52
|
+
// The same answer for a missing document and a document of another user.
|
|
53
|
+
const file = await ctx.runQuery(internal.documents.forDownload, { id, userId: user.id })
|
|
54
|
+
if (!file) return new Response(null, { status: 404, headers: noStore })
|
|
55
|
+
const blob = await ctx.storage.get(file.storageId)
|
|
56
|
+
if (!blob) return new Response(null, { status: 404, headers: noStore })
|
|
57
|
+
return new Response(blob, {
|
|
58
|
+
headers: {
|
|
59
|
+
...noStore,
|
|
60
|
+
'content-type': file.contentType,
|
|
61
|
+
'content-length': String(blob.size),
|
|
62
|
+
'content-disposition': `inline; filename*=UTF-8''${encodeURIComponent(file.fileName)}`,
|
|
63
|
+
'x-content-type-options': 'nosniff',
|
|
64
|
+
},
|
|
65
|
+
})
|
|
66
|
+
}),
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
export default http
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`auth.getUser(ctx)` reads the `Authorization: Bearer` header and checks the live
|
|
73
|
+
session, as in a query. `internal.documents.forDownload` is your own internal
|
|
74
|
+
query. It turns `id` into a document ID with `ctx.db.normalizeId`, checks that
|
|
75
|
+
the user may read the document, and returns its storage ID, type and name, or
|
|
76
|
+
`null`. Store the type that you found in the file's bytes at upload,
|
|
77
|
+
not the type the uploader declared.
|
|
78
|
+
|
|
79
|
+
Do not mount this route under `/api/auth/`. The auth proxy refuses responses
|
|
80
|
+
larger than 1 MiB.
|
|
81
|
+
|
|
82
|
+
## Call it from a Nuxt server route
|
|
83
|
+
|
|
84
|
+
```ts [server/routes/files/[id\].get.ts]
|
|
85
|
+
import { defineEventHandler, getRouterParam } from 'nuxt/server'
|
|
86
|
+
import { serverConvex } from '#convex/server'
|
|
87
|
+
|
|
88
|
+
export default defineEventHandler(async (event) => {
|
|
89
|
+
const id = getRouterParam(event, 'id') ?? ''
|
|
90
|
+
const noStore = { 'cache-control': 'private, no-store' }
|
|
91
|
+
if (!/^[a-z0-9]{10,64}$/.test(id)) return new Response(null, { status: 404, headers: noStore })
|
|
92
|
+
|
|
93
|
+
const upstream = await serverConvex(event).fetch(`/files/${id}`)
|
|
94
|
+
if (!upstream.ok)
|
|
95
|
+
return new Response(null, { status: upstream.status === 401 ? 401 : 404, headers: noStore })
|
|
96
|
+
|
|
97
|
+
const headers = new Headers(noStore)
|
|
98
|
+
for (const name of [
|
|
99
|
+
'content-type',
|
|
100
|
+
'content-length',
|
|
101
|
+
'content-disposition',
|
|
102
|
+
'x-content-type-options',
|
|
103
|
+
]) {
|
|
104
|
+
const value = upstream.headers.get(name)
|
|
105
|
+
if (value) headers.set(name, value)
|
|
106
|
+
}
|
|
107
|
+
return new Response(upstream.body, { headers })
|
|
108
|
+
})
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
`fetch(path)` sends a `GET` to the Convex HTTP actions host of the deployment,
|
|
112
|
+
with the caller's Convex session token as `Authorization: Bearer`. It returns the
|
|
113
|
+
upstream `Response` and streams its body. Copy only the headers that you need.
|
|
114
|
+
|
|
115
|
+
## Cost and limits
|
|
116
|
+
|
|
117
|
+
- Each download runs the HTTP action, one query and one storage read, and Convex
|
|
118
|
+
bills the bytes the action sends.
|
|
119
|
+
- Convex limits an HTTP action response to 100 MiB. `fetch` does not apply the
|
|
120
|
+
1 MiB cap of `query`, `mutation` and `action`, so a large file passes through
|
|
121
|
+
your Nuxt server.
|
|
122
|
+
- `fetch` forwards no request headers from the browser, so `Range` requests do
|
|
123
|
+
not work: no seeking in a video and no resumed download. Each request sends
|
|
124
|
+
the whole file.
|
|
125
|
+
- `Cache-Control: private, no-store` keeps shared caches from storing one
|
|
126
|
+
person's file for another.
|
|
@@ -15,6 +15,11 @@ source: "ginko-content"
|
|
|
15
15
|
|
|
16
16
|
Store Convex storage IDs in product data. Resolve a URL with `useConvexQuery` when the UI needs it.
|
|
17
17
|
|
|
18
|
+
A storage URL works for anyone who has it, and it does not expire. Convex
|
|
19
|
+
revokes it only when the file is deleted. When access to a file must end, for
|
|
20
|
+
example when a member leaves a workspace, serve it through a
|
|
21
|
+
[private download route](./private-downloads.md) instead.
|
|
22
|
+
|
|
18
23
|
## Backend query
|
|
19
24
|
|
|
20
25
|
```ts [convex/documents.ts]
|
|
@@ -39,7 +44,7 @@ The query takes a document ID, not a storage ID. Anyone who knows a storage ID c
|
|
|
39
44
|
## Reactive URL
|
|
40
45
|
|
|
41
46
|
```ts
|
|
42
|
-
import type { Id } from '
|
|
47
|
+
import type { Id } from '#convex/dataModel'
|
|
43
48
|
|
|
44
49
|
const documentId = ref<Id<'documents'> | undefined>()
|
|
45
50
|
const urlArgs = computed(() => (documentId.value ? { documentId: documentId.value } : 'skip'))
|
|
@@ -59,7 +64,7 @@ The query is idle until a document ID exists and runs again when it changes. Use
|
|
|
59
64
|
|
|
60
65
|
```ts
|
|
61
66
|
import type { UploadCompleteContext } from '@lupinum/better-convex-nuxt'
|
|
62
|
-
import type { Id } from '
|
|
67
|
+
import type { Id } from '#convex/dataModel'
|
|
63
68
|
|
|
64
69
|
const props = defineProps<{ documentId: Id<'documents'> }>()
|
|
65
70
|
|
|
@@ -86,4 +91,4 @@ await upload(file, { context: props.documentId })
|
|
|
86
91
|
|
|
87
92
|
## URL lifetime
|
|
88
93
|
|
|
89
|
-
Treat the resolved URL as presentation data. Store the branded storage ID on the document as the durable reference and resolve again when needed. See [Upload files](./upload-files.md#attach-the-file-safely) for `attachFile`.
|
|
94
|
+
Treat the resolved URL as presentation data. It stays valid until the file is deleted, also for a person who has lost access. Store the branded storage ID on the document as the durable reference and resolve again when needed. See [Upload files](./upload-files.md#attach-the-file-safely) for `attachFile`.
|
|
@@ -135,7 +135,7 @@ The upload step only creates a storage object. Record it in a document with `com
|
|
|
135
135
|
|
|
136
136
|
```ts
|
|
137
137
|
import type { UploadCompleteContext } from '@lupinum/better-convex-nuxt'
|
|
138
|
-
import type { Id } from '
|
|
138
|
+
import type { Id } from '#convex/dataModel'
|
|
139
139
|
|
|
140
140
|
const props = defineProps<{ documentId: Id<'documents'> }>()
|
|
141
141
|
|
|
@@ -296,7 +296,7 @@ The library keeps the universal one-file primitive small. If a product needs mul
|
|
|
296
296
|
This example creates three upload workers during setup and records durable results separately from each worker's transient progress:
|
|
297
297
|
|
|
298
298
|
```ts
|
|
299
|
-
import type { Id } from '
|
|
299
|
+
import type { Id } from '#convex/dataModel'
|
|
300
300
|
|
|
301
301
|
const workers = [
|
|
302
302
|
useConvexFileUpload(api.files.generateUploadUrl),
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
|
-
title: "Rate limits and
|
|
3
|
-
description: "Limit how often an action runs
|
|
2
|
+
title: "Rate limits, audit log and call events"
|
|
3
|
+
description: "Limit how often an action runs, keep a record of who changed which rows, and send one event per call to your log service."
|
|
4
4
|
url: "https://better-convex.lupinum.com/docs/build/functions/limits-and-audit"
|
|
5
5
|
route: "/docs/build/functions/limits-and-audit"
|
|
6
6
|
locale: "en"
|
|
@@ -9,9 +9,9 @@ collection: "docs"
|
|
|
9
9
|
source: "ginko-content"
|
|
10
10
|
---
|
|
11
11
|
|
|
12
|
-
# Rate limits and
|
|
12
|
+
# Rate limits, audit log and call events
|
|
13
13
|
|
|
14
|
-
> Limit how often an action runs
|
|
14
|
+
> Limit how often an action runs, keep a record of who changed which rows, and send one event per call to your log service.
|
|
15
15
|
|
|
16
16
|
Both are written in the policy, next to the roles. There is no second place to
|
|
17
17
|
configure them.
|
|
@@ -175,3 +175,141 @@ It returns one page of the tenant's rows, newest first. No retention is
|
|
|
175
175
|
applied: the log is meant to last. When a person deletes their account,
|
|
176
176
|
[erasure](../authentication/account-deletion.md) removes their id from
|
|
177
177
|
the rows and keeps the rows themselves.
|
|
178
|
+
|
|
179
|
+
## Call events
|
|
180
|
+
|
|
181
|
+
Turn on `observe` to write one line on the console for each call. A
|
|
182
|
+
[Convex log stream](https://docs.convex.dev/production/integrations/log-streams)
|
|
183
|
+
(Convex Pro plan) sends the lines to your log service.
|
|
184
|
+
[Log streams and PostHog](../../operations/log-streams.md) shows how to connect
|
|
185
|
+
one and find a call.
|
|
186
|
+
|
|
187
|
+
```ts [convex/functions.ts]
|
|
188
|
+
export const fns = defineFunctions({
|
|
189
|
+
auth,
|
|
190
|
+
policy,
|
|
191
|
+
user,
|
|
192
|
+
roleOf,
|
|
193
|
+
rules,
|
|
194
|
+
observe: true,
|
|
195
|
+
})
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Each call that reaches your function writes one JSON line:
|
|
199
|
+
|
|
200
|
+
```json
|
|
201
|
+
{
|
|
202
|
+
"type": "better-convex.call",
|
|
203
|
+
"action": "projects.archive",
|
|
204
|
+
"kind": "mutation",
|
|
205
|
+
"actor": { "key": "person:k57…", "kind": "person", "door": "web", "userId": "k57…" },
|
|
206
|
+
"tenant": "j97…",
|
|
207
|
+
"outcome": "error",
|
|
208
|
+
"code": "FORBIDDEN"
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
| Field | Content |
|
|
213
|
+
| --- | --- |
|
|
214
|
+
| `action` | The policy action. A job writes `job.<name>`. An internal action has none. The agents package's own functions write `agents.<name>`. |
|
|
215
|
+
| `kind` | `query`, `mutation` or `action`. |
|
|
216
|
+
| `actor` | The same record as in `auditLog`, or `{ "kind": "visitor" }`. An internal action shows only the kind it acts for, such as `{ "kind": "person" }`, without `key`. Missing when the call failed before it knew the caller. |
|
|
217
|
+
| `agent` | The key of the agent whose request a person approved or declined. `actor` is that person. |
|
|
218
|
+
| `tenant` | The call's tenant, when it has one. |
|
|
219
|
+
| `outcome` | `ok` or `error`. For an agent's request: `pending` while it waits for a person, `declined` when a person declined it. |
|
|
220
|
+
| `code` | The `data.code` of the `ConvexError`: a library code or your app's own. A crash has none. |
|
|
221
|
+
| `written` | How many rows a call that succeeded inserted, patched, replaced or deleted. Missing for work that runs as the system, such as a job: its writes are not counted. |
|
|
222
|
+
| `approval` | The approval request an agent's call made, or the one its work runs under. |
|
|
223
|
+
| `trace` | The ID of the chain of calls this call belongs to (see below). Missing on a call that starts no other work. |
|
|
224
|
+
| `fields` | What the handler added with `ctx.log.set`. A value JSON cannot hold, such as a BigInt, is left out. |
|
|
225
|
+
|
|
226
|
+
A query writes a line only when it fails, because Convex runs a query again
|
|
227
|
+
each time the rows it read change. A mutation that fails also writes its line:
|
|
228
|
+
its writes roll back, but the console line stays.
|
|
229
|
+
|
|
230
|
+
One transaction writes one line. An internal operation that a query or mutation
|
|
231
|
+
runs with `ctx.runQuery` or `ctx.runMutation` is part of the caller's
|
|
232
|
+
transaction, so it writes no line of its own. The caller's line counts its rows
|
|
233
|
+
in `written` and shows its `ctx.log.set` fields. Calls from an action and
|
|
234
|
+
scheduled work run on their own and write their own lines. A job argument
|
|
235
|
+
cannot be named `inner`.
|
|
236
|
+
|
|
237
|
+
When the caller catches the failure of such an inner call, its line shows only
|
|
238
|
+
its own outcome: `ok`, without the inner call's code.
|
|
239
|
+
|
|
240
|
+
`ok` means that your handler finished. Convex can still fail the call after
|
|
241
|
+
that, when the result does not match `returns`. Convex also refuses arguments
|
|
242
|
+
that do not match `args` before your handler runs, and then no line is written.
|
|
243
|
+
Convex's own event for the same request ID has the final status.
|
|
244
|
+
|
|
245
|
+
A public action that its policy check refuses also writes a line, with the
|
|
246
|
+
actor and the tenant of the call.
|
|
247
|
+
|
|
248
|
+
### Agents
|
|
249
|
+
|
|
250
|
+
With the [agents package](../agents/tools-and-approvals.md), each tool
|
|
251
|
+
call writes a line with the agent as `actor`, except a query tool that
|
|
252
|
+
succeeds, like any query. A call the library refuses before
|
|
253
|
+
your function runs writes one too: a revoked connection (`AGENT_DISABLED`), a
|
|
254
|
+
connection over its limit (`RATE_LIMITED`) or input that does not fit
|
|
255
|
+
(`INVALID_INPUT`).
|
|
256
|
+
|
|
257
|
+
A tool call that needs a person's approval writes `outcome: "pending"` and the
|
|
258
|
+
request in `approval`. The person's decision writes the next line for the same
|
|
259
|
+
request, with the request's action:
|
|
260
|
+
|
|
261
|
+
```json
|
|
262
|
+
{
|
|
263
|
+
"type": "better-convex.call",
|
|
264
|
+
"action": "projects.archive",
|
|
265
|
+
"kind": "mutation",
|
|
266
|
+
"actor": { "key": "person:k57…", "kind": "person", "door": "web", "userId": "k57…" },
|
|
267
|
+
"agent": "mcp:k57…:claude-desktop",
|
|
268
|
+
"tenant": "j97…",
|
|
269
|
+
"outcome": "ok",
|
|
270
|
+
"written": 1,
|
|
271
|
+
"approval": "jd7…"
|
|
272
|
+
}
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
The approved work runs inside `approve` and writes no line of its own. The line
|
|
276
|
+
of `approve` shows the outcome of the work: `ok` with its rows, or `error` with
|
|
277
|
+
its code, for example `STALE` when a row changed after the agent asked. A
|
|
278
|
+
decline writes `outcome: "declined"`.
|
|
279
|
+
|
|
280
|
+
`housekeeping`, the upload route, and the steps of in-app agents write no line.
|
|
281
|
+
The tool calls those steps make do.
|
|
282
|
+
|
|
283
|
+
### What the line holds
|
|
284
|
+
|
|
285
|
+
The line holds IDs and codes, never arguments, results or messages. You can
|
|
286
|
+
add your own IDs with `ctx.log.set`. Do not add values that a person typed,
|
|
287
|
+
such as names, amounts or email addresses: the log stream copies every line to
|
|
288
|
+
another service.
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
handler: async (ctx, { documentId }) => {
|
|
292
|
+
ctx.log.set({ document: { id: documentId } })
|
|
293
|
+
// …
|
|
294
|
+
}
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
Without `observe`, `ctx.log.set` does nothing.
|
|
298
|
+
|
|
299
|
+
Convex writes its own event for each call, with the function path, the
|
|
300
|
+
duration, the final status and the request ID. Find both events by the request
|
|
301
|
+
ID that [`error.requestId`](../application-behavior/error-handling.md#quote-the-request-id)
|
|
302
|
+
shows the user. `observe` reads and writes no table and changes no query
|
|
303
|
+
subscription.
|
|
304
|
+
|
|
305
|
+
Convex gives scheduled work a new request ID, and its event does not name the
|
|
306
|
+
call that scheduled it. So a call that starts other work (`ctx.scheduler`,
|
|
307
|
+
`ctx.runQuery`, `ctx.runMutation` or `ctx.runAction`) gets a `trace` ID and
|
|
308
|
+
passes it on. Each internal operation, internal action and job in the chain
|
|
309
|
+
writes the same `trace`, also when it runs hours later. Search for one `trace`
|
|
310
|
+
to see everything that one call started. A job argument cannot be named
|
|
311
|
+
`trace`.
|
|
312
|
+
|
|
313
|
+
The audit log and call events answer different questions. The audit log stays
|
|
314
|
+
in your database and records who changed which rows. Call events leave Convex
|
|
315
|
+
and also record refused and failed calls.
|