@vllnt/convex-invitations 0.1.0 → 0.1.1-canary.009f81e

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 (62) hide show
  1. package/CHANGELOG.md +117 -0
  2. package/README.md +444 -80
  3. package/dist/client/index.d.ts +9 -7
  4. package/dist/client/index.d.ts.map +1 -1
  5. package/dist/client/index.js +9 -7
  6. package/dist/client/index.js.map +1 -1
  7. package/dist/client/types.d.ts +7 -4
  8. package/dist/client/types.d.ts.map +1 -1
  9. package/dist/component/convex.config.d.ts +1 -0
  10. package/dist/component/convex.config.d.ts.map +1 -1
  11. package/dist/component/convex.config.js +1 -0
  12. package/dist/component/convex.config.js.map +1 -1
  13. package/dist/component/crons.js +1 -1
  14. package/dist/component/crons.js.map +1 -1
  15. package/dist/component/guards.d.ts +7 -0
  16. package/dist/component/guards.d.ts.map +1 -0
  17. package/dist/component/guards.js +23 -0
  18. package/dist/component/guards.js.map +1 -0
  19. package/dist/component/legacyToken.d.ts +4 -2
  20. package/dist/component/legacyToken.d.ts.map +1 -1
  21. package/dist/component/legacyToken.js +2 -0
  22. package/dist/component/legacyToken.js.map +1 -1
  23. package/dist/component/mutations.d.ts +3 -3
  24. package/dist/component/mutations.d.ts.map +1 -1
  25. package/dist/component/mutations.js +29 -10
  26. package/dist/component/mutations.js.map +1 -1
  27. package/dist/component/queries.d.ts +1 -1
  28. package/dist/component/queries.d.ts.map +1 -1
  29. package/dist/component/queries.js +9 -6
  30. package/dist/component/queries.js.map +1 -1
  31. package/dist/component/schema.d.ts +2 -2
  32. package/dist/component/schema.js +3 -3
  33. package/dist/component/schema.js.map +1 -1
  34. package/dist/component/token.d.ts +3 -0
  35. package/dist/component/token.d.ts.map +1 -1
  36. package/dist/component/token.js +6 -1
  37. package/dist/component/token.js.map +1 -1
  38. package/dist/component/validators.d.ts +7 -4
  39. package/dist/component/validators.d.ts.map +1 -1
  40. package/dist/component/validators.js +7 -4
  41. package/dist/component/validators.js.map +1 -1
  42. package/dist/shared.d.ts +5 -3
  43. package/dist/shared.d.ts.map +1 -1
  44. package/dist/shared.js +5 -3
  45. package/dist/shared.js.map +1 -1
  46. package/docs/API.md +320 -0
  47. package/llms.txt +65 -0
  48. package/package.json +48 -25
  49. package/src/client/index.ts +9 -7
  50. package/src/client/types.ts +7 -4
  51. package/src/component/convex.config.ts +1 -0
  52. package/src/component/crons.ts +1 -1
  53. package/src/component/guards.ts +26 -0
  54. package/src/component/legacyToken.ts +4 -2
  55. package/src/component/mutations.ts +25 -10
  56. package/src/component/queries.ts +9 -7
  57. package/src/component/schema.ts +3 -3
  58. package/src/component/token.ts +7 -1
  59. package/src/component/validators.ts +7 -4
  60. package/src/shared.ts +5 -3
  61. package/src/test.ts +9 -2
  62. package/src/component/migration.test.ts +0 -110
package/README.md CHANGED
@@ -1,49 +1,37 @@
1
- <!-- Badges -->
2
- [![convex-component](https://img.shields.io/badge/convex-component-EE342F.svg)](https://www.convex.dev/components)
3
- [![npm](https://img.shields.io/npm/v/@vllnt/convex-invitations.svg)](https://www.npmjs.com/package/@vllnt/convex-invitations)
4
- [![CI](https://github.com/vllnt/convex-invitations/actions/workflows/ci.yml/badge.svg)](https://github.com/vllnt/convex-invitations/actions/workflows/ci.yml)
5
- [![license](https://img.shields.io/npm/l/@vllnt/convex-invitations.svg)](./LICENSE)
6
-
7
1
  # @vllnt/convex-invitations
8
2
 
9
- The invite → accept → expire flow, as a Convex component.
3
+ TypeScript Convex component for single-use, expiring invitation links: issue,
4
+ accept once, revoke, expire and prune invites.
10
5
 
11
- ```ts
12
- const invites = new Invitations(components.invitations);
13
- const { token } = await invites.issue(ctx, orgId, { role: "member" }); // host delivers token
14
- const grant = await invites.accept(ctx, token, userId); // single-use; host applies grant
15
- ```
6
+ ## For coding agents
16
7
 
17
- A host mutation issues a single-use, expiring invitation to an opaque resource and
18
- gets back a token to deliver out of band; the invitee redeems it with `accept`,
19
- which consumes the invite and returns the grant the host applies. Domain-neutral: a
20
- game guild invite, a SaaS workspace invite, a publication contributor invite.
8
+ Docs for the installed version are in `node_modules/@vllnt/convex-invitations/docs/`,
9
+ next to `llms.txt`, `CHANGELOG.md` and the TypeScript `src/`. Read them before
10
+ writing code against this package.
21
11
 
22
- ## Features
12
+ ## When to use
23
13
 
24
- - **Issue-and-deliver** — `issue` inserts a `pending` invite, returns a single-use `token` + `expiresAt`; the host delivers it (never sends email).
25
- - **Single-use accept** — `accept` consumes the invite and returns the grant (`resourceRef` + opaque `role`/`payload`) the host applies.
26
- - **Terminal states are final** — `accepted`/`revoked`/`expired` are terminal; a replayed link can never double-grant.
27
- - **TTL + expiry** — every invite carries an `expiresAt`; accepting past-TTL is rejected; a daily cron and `peek` sweep stale invites.
28
- - **Revoke** — `revoke` cancels a still-`pending` invite; a revoke racing an accept yields exactly one winner.
29
- - **Poll or subscribe** — `getByToken`, `listPending`, and `listByResourceState` page invites reactively in Convex.
30
- - **Typed, opaque host data** — `Invitations<TRole, TPayload>` with optional `roleValidator`/`payloadValidator` at the boundary; server-sourced time.
31
- - **Bounded prune + cron, mount-safe** — a daily cron expires + prunes in idempotent batches; correct under multiple named mounts.
14
+ - Use it when someone joins an org, team or workspace through a link that works
15
+ once and expires.
16
+ - Use it when an open invite must be revocable and a replayed or concurrent
17
+ accept must never grant twice.
18
+ - Do not use it when you need sign-in links, password resets or user accounts:
19
+ use `@convex-dev/auth`.
20
+ - Do not use it when you need the invite email sent: it returns the token and
21
+ sends nothing; use `@convex-dev/resend` or your own mailer.
32
22
 
33
- ## Installation
23
+ ## Install
34
24
 
35
25
  ```bash
36
- pnpm add @vllnt/convex-invitations
26
+ pnpm add @vllnt/convex-invitations convex
37
27
  ```
38
28
 
39
- Peer dependency: `convex@^1.41.0`.
40
-
41
- ## Usage
29
+ ## Quick start
42
30
 
43
31
  ```ts
44
32
  // convex/convex.config.ts
45
- import { defineApp } from "convex/server";
46
33
  import invitations from "@vllnt/convex-invitations/convex.config";
34
+ import { defineApp } from "convex/server";
47
35
 
48
36
  const app = defineApp();
49
37
  app.use(invitations);
@@ -51,89 +39,465 @@ export default app;
51
39
  ```
52
40
 
53
41
  ```ts
54
- // convex/invites.ts — host owns auth, the resource meaning, and delivery.
42
+ // convex/schema.ts
43
+ import { defineSchema, defineTable } from "convex/server";
44
+ import { v } from "convex/values";
45
+
46
+ export default defineSchema({
47
+ memberships: defineTable({
48
+ orgId: v.string(),
49
+ userRef: v.string(),
50
+ role: v.union(v.literal("admin"), v.literal("member")),
51
+ }).index("by_org_user", ["orgId", "userRef"]),
52
+ });
53
+ ```
54
+
55
+ ```ts
56
+ // convex/invites.ts
57
+ import { Invitations } from "@vllnt/convex-invitations";
58
+ import { ConvexError, v } from "convex/values";
59
+
55
60
  import { components } from "./_generated/api";
56
61
  import { mutation } from "./_generated/server";
57
- import { v } from "convex/values";
62
+
63
+ type Role = "admin" | "member";
64
+ const role = v.union(v.literal("admin"), v.literal("member"));
65
+
66
+ const invites = new Invitations<Role>(components.invitations, {
67
+ roleValidator: (value) => {
68
+ if (value !== "admin" && value !== "member") throw new Error("bad role");
69
+ return value;
70
+ },
71
+ });
72
+
73
+ export const createInvite = mutation({
74
+ args: { orgId: v.string(), role },
75
+ returns: v.object({ token: v.string(), expiresAt: v.number() }),
76
+ handler: async (ctx, args) => {
77
+ const user = await ctx.auth.getUserIdentity();
78
+ if (user === null) throw new ConvexError("not signed in");
79
+ // Check here that `user` may invite people to `args.orgId`.
80
+ return invites.issue(ctx, args.orgId, {
81
+ role: args.role,
82
+ inviterRef: user.tokenIdentifier,
83
+ });
84
+ },
85
+ });
86
+
87
+ export const acceptInvite = mutation({
88
+ args: { token: v.string() },
89
+ returns: v.object({ orgId: v.string(), role }),
90
+ handler: async (ctx, { token }) => {
91
+ const user = await ctx.auth.getUserIdentity();
92
+ if (user === null) throw new ConvexError("not signed in");
93
+ const grant = await invites.accept(ctx, token, user.tokenIdentifier);
94
+ const membership = {
95
+ orgId: grant.resourceRef,
96
+ userRef: user.tokenIdentifier,
97
+ role: grant.role ?? "member",
98
+ };
99
+ // Same mutation: if this write fails, the accept rolls back too.
100
+ await ctx.db.insert("memberships", membership);
101
+ return { orgId: membership.orgId, role: membership.role };
102
+ },
103
+ });
104
+ ```
105
+
106
+ Run `npx convex dev` once to generate `components.invitations`. Deliver the
107
+ returned `token` yourself (for example in a `https://example.com/join?token=<token>` link).
108
+ The component never reads auth: the host decides who may issue, accept and
109
+ revoke, and applies the returned grant.
110
+
111
+ ## API
112
+
113
+ Full reference: [docs/API.md](docs/API.md).
114
+
115
+ | Export | Import from | What it does |
116
+ | -------------------------------------------------------------------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------- |
117
+ | [`Invitations`](docs/API.md#invitations) | `@vllnt/convex-invitations` | Host client: `new Invitations(components.invitations, options?)` |
118
+ | [`issue(ctx, resourceRef, opts?)`](docs/API.md#issue) | `Invitations` method, mutation | Create a `pending` invite; returns `{ token, expiresAt }` |
119
+ | [`accept(ctx, token, acceptedBy)`](docs/API.md#accept) | `Invitations` method, mutation | Consume a `pending` invite once; returns the grant |
120
+ | [`revoke(ctx, token)`](docs/API.md#revoke) | `Invitations` method, mutation | `pending` -> `revoked`; returns `null` |
121
+ | [`peek(ctx, token)`](docs/API.md#peek) | `Invitations` method, mutation | Read one invite; stores `expired` if its TTL passed |
122
+ | [`getByToken(ctx, token)`](docs/API.md#getbytoken) | `Invitations` method, query | Read one invite as stored, or `null` |
123
+ | [`listPending(ctx, resourceRef, paginationOpts)`](docs/API.md#listpending) | `Invitations` method, query | One page of `pending` invites for a resource, without tokens |
124
+ | [`listByResourceState(ctx, resourceRef, state, paginationOpts)`](docs/API.md#listbyresourcestate) | `Invitations` method, query | One page of invites in one state for a resource, without tokens |
125
+ | [`migrateLegacyTokens(ctx, batch?)`](docs/API.md#migratelegacytokens) | `Invitations` method, mutation | Replace stored raw tokens from older rows with digests |
126
+ | [`prune(ctx, opts?)`](docs/API.md#prune) | `Invitations` method, mutation | Delete old terminal invites and expire stale `pending` ones |
127
+ | [`InvitationsComponent`](docs/API.md#invitationscomponent) | `@vllnt/convex-invitations` (type) | Type of `components.invitations` |
128
+ | [`InvitationsOptions`](docs/API.md#invitationsoptions) | `@vllnt/convex-invitations` (type) | `{ ttlMs?, generateToken?, roleValidator?, payloadValidator? }` |
129
+ | [`IssueOptions`](docs/API.md#issueoptions) | `@vllnt/convex-invitations` (type) | `{ role?, inviterRef?, inviteeRef?, payload?, ttlMs?, expiresAt? }` |
130
+ | [`InvitationGrant`](docs/API.md#invitationgrant) | `@vllnt/convex-invitations` (type) | Result of `accept`: `{ resourceRef, role?, payload? }` |
131
+ | [`InvitationView`](docs/API.md#invitationview) | `@vllnt/convex-invitations` (type) | Result of `peek` and `getByToken` |
132
+ | [`InvitationMetadata`](docs/API.md#invitationmetadata) | `@vllnt/convex-invitations` (type) | List row: `InvitationView` without `token` |
133
+ | [`InvitationState`](docs/API.md#invitationstate) | `@vllnt/convex-invitations` (type) | `"pending" \| "accepted" \| "revoked" \| "expired"` |
134
+ | [`Parser`](docs/API.md#parser) | `@vllnt/convex-invitations` (type) | `(value: unknown) => T`, used by `roleValidator`/`payloadValidator` |
135
+ | [`default` (component config)](docs/API.md#convexconfig) | `@vllnt/convex-invitations/convex.config` | Pass to `app.use(...)` |
136
+ | [`register`](docs/API.md#register) | `@vllnt/convex-invitations/test` | Mount the component in `convex-test` |
137
+ | [`ComponentApi`](docs/API.md#componentapi) | `@vllnt/convex-invitations/_generated/component` | Generated type of the mounted component |
138
+
139
+ ## Common tasks
140
+
141
+ Show an invite page before the user accepts. `getByToken` is a reactive query
142
+ that reports the stored state, so an expired link can still read `pending`;
143
+ compare `expiresAt` with the clock on the client:
144
+
145
+ ```ts
146
+ // convex/invitePage.ts
58
147
  import { Invitations } from "@vllnt/convex-invitations";
148
+ import { v } from "convex/values";
59
149
 
60
- const invites = new Invitations<"admin" | "member", never>(components.invitations, {
61
- ttlMs: 1000 * 60 * 60 * 24 * 3, // 3-day links
62
- roleValidator: v.union(v.literal("admin"), v.literal("member")).parse,
150
+ import { components } from "./_generated/api";
151
+ import { query } from "./_generated/server";
152
+
153
+ const invites = new Invitations(components.invitations);
154
+
155
+ export const invitePage = query({
156
+ args: { token: v.string() },
157
+ returns: v.union(
158
+ v.null(),
159
+ v.object({ orgId: v.string(), state: v.string(), expiresAt: v.number() }),
160
+ ),
161
+ handler: async (ctx, { token }) => {
162
+ const invite = await invites.getByToken(ctx, token);
163
+ if (invite === null) return null;
164
+ return {
165
+ orgId: invite.resourceRef,
166
+ state: invite.state,
167
+ expiresAt: invite.expiresAt,
168
+ };
169
+ },
63
170
  });
171
+ ```
172
+
173
+ List an org's open invites for an admin screen. List rows never include the
174
+ token, so keep the token yourself at `issue` time if you need to revoke or
175
+ resend from this screen:
176
+
177
+ ```ts
178
+ // convex/openInvites.ts
179
+ import { Invitations } from "@vllnt/convex-invitations";
180
+ import { paginationOptsValidator } from "convex/server";
181
+ import { v } from "convex/values";
182
+
183
+ import { components } from "./_generated/api";
184
+ import { query } from "./_generated/server";
185
+
186
+ const invites = new Invitations(components.invitations);
64
187
 
65
- // Issue: record the invite, return the token to deliver.
66
- export const invite = mutation({
67
- args: { orgId: v.string(), role: v.union(v.literal("admin"), v.literal("member")) },
68
- handler: async (ctx, { orgId, role }) => {
69
- const { token } = await invites.issue(ctx, orgId, { role }); // host gates the caller first
70
- return { token }; // host emails `https://app/join?token=${token}`
188
+ export const openInvites = query({
189
+ args: { orgId: v.string(), paginationOpts: paginationOptsValidator },
190
+ returns: v.object({
191
+ continueCursor: v.string(),
192
+ isDone: v.boolean(),
193
+ page: v.array(
194
+ v.object({ inviteeRef: v.optional(v.string()), expiresAt: v.number() }),
195
+ ),
196
+ }),
197
+ handler: async (ctx, { orgId, paginationOpts }) => {
198
+ // Check here that the caller may see `orgId`'s invites.
199
+ const result = await invites.listPending(ctx, orgId, paginationOpts);
200
+ return {
201
+ continueCursor: result.continueCursor,
202
+ isDone: result.isDone,
203
+ page: result.page.map((invite) => ({
204
+ inviteeRef: invite.inviteeRef,
205
+ expiresAt: invite.expiresAt,
206
+ })),
207
+ };
71
208
  },
72
209
  });
210
+ ```
73
211
 
74
- // Accept: consume the invite, apply the grant (write your own membership).
75
- export const join = mutation({
212
+ Revoke an invite, and turn an accept failure into a result instead of an
213
+ exception. Errors are `ConvexError`s whose `data.code` is listed under
214
+ [Errors and fixes](#errors-and-fixes):
215
+
216
+ ```ts
217
+ // convex/manageInvites.ts
218
+ import { Invitations } from "@vllnt/convex-invitations";
219
+ import { ConvexError, v } from "convex/values";
220
+
221
+ import { components } from "./_generated/api";
222
+ import { internalMutation, mutation } from "./_generated/server";
223
+
224
+ const invites = new Invitations(components.invitations);
225
+
226
+ export const revokeInvite = internalMutation({
76
227
  args: { token: v.string() },
228
+ returns: v.null(),
229
+ handler: (ctx, { token }) => invites.revoke(ctx, token),
230
+ });
231
+
232
+ const codeOf = (error: unknown): string | undefined => {
233
+ if (!(error instanceof ConvexError)) return undefined;
234
+ const data: unknown = error.data;
235
+ if (typeof data !== "object" || data === null || !("code" in data)) {
236
+ return undefined;
237
+ }
238
+ return typeof data.code === "string" ? data.code : undefined;
239
+ };
240
+
241
+ export const tryAccept = mutation({
242
+ args: { token: v.string() },
243
+ returns: v.object({ ok: v.boolean(), code: v.optional(v.string()) }),
77
244
  handler: async (ctx, { token }) => {
78
- const me = await currentUser(ctx); // host resolves identity
79
- const grant = await invites.accept(ctx, token, me);
80
- await ctx.db.insert("memberships", { orgId: grant.resourceRef, userId: me, role: grant.role });
245
+ const user = await ctx.auth.getUserIdentity();
246
+ if (user === null) throw new ConvexError("not signed in");
247
+ try {
248
+ await invites.accept(ctx, token, user.tokenIdentifier);
249
+ return { ok: true };
250
+ } catch (error) {
251
+ const code = codeOf(error);
252
+ if (code === undefined) throw error;
253
+ return { ok: false, code };
254
+ }
81
255
  },
82
256
  });
83
257
  ```
84
258
 
85
- Client options: `new Invitations(component, { ttlMs?, generateToken?, roleValidator?, payloadValidator? })`.
259
+ Keep terminal invites for less than the default 30 days by calling `prune`
260
+ from your own cron. The built-in daily cron still runs with 30 days, so a
261
+ longer window has no effect:
86
262
 
87
- ## API Reference
263
+ ```ts
264
+ // convex/maintenance.ts
265
+ import { Invitations } from "@vllnt/convex-invitations";
266
+ import { v } from "convex/values";
88
267
 
89
- | Method | Kind | Result |
90
- |--------|------|--------|
91
- | `issue(ctx, resourceRef, opts?)` | mutation | `{ token, expiresAt }` (`opts`: `{ role?; inviterRef?; inviteeRef?; payload?; ttlMs?; expiresAt? }`) |
92
- | `accept(ctx, token, acceptedBy)` | mutation | `InvitationGrant` (`{ resourceRef; role?; payload? }`) |
93
- | `revoke(ctx, token)` | mutation | `null` |
94
- | `peek(ctx, token)` | mutation | `InvitationView \| null` (read-time TTL enforcement) |
95
- | `getByToken(ctx, token)` | query | `InvitationView \| null` (pure reactive read) |
96
- | `listPending(ctx, resourceRef, paginationOpts)` | query | `PaginationResult<InvitationView>` |
97
- | `listByResourceState(ctx, resourceRef, state, paginationOpts)` | query | `PaginationResult<InvitationView>` |
98
- | `prune(ctx, opts?)` | mutation | `number` (invites touched in the first bounded pass) |
268
+ import { components } from "./_generated/api";
269
+ import { internalMutation } from "./_generated/server";
99
270
 
100
- Full reference: [docs/API.md](docs/API.md).
271
+ const invites = new Invitations(components.invitations);
272
+ const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
101
273
 
102
- ## React
274
+ export const pruneAfterAWeek = internalMutation({
275
+ args: {},
276
+ returns: v.number(),
277
+ handler: (ctx) =>
278
+ invites.prune(ctx, { retentionBefore: Date.now() - WEEK_MS }),
279
+ });
280
+ ```
103
281
 
104
- Backend-only — no `./react` entry. An invite-management surface is an ordinary
105
- reactive `useQuery` over the host's own re-exported `getByToken` / `listPending`
106
- refs; the token is delivered by the host, never revealed in a client component.
282
+ ```ts
283
+ // convex/crons.ts
284
+ import { cronJobs } from "convex/server";
285
+
286
+ import { internal } from "./_generated/api";
287
+
288
+ const crons = cronJobs();
289
+ crons.daily(
290
+ "prune invitations after a week",
291
+ { hourUTC: 3, minuteUTC: 0 },
292
+ internal.maintenance.pruneAfterAWeek,
293
+ {},
294
+ );
295
+ export default crons;
296
+ ```
107
297
 
108
- ## Security
298
+ Mount the component twice. Each named mount has its own table and its own
299
+ crons, and shares nothing with the other:
109
300
 
110
- - **Auth-agnostic** — the host authenticates the caller, decides who may issue/accept/revoke, and owns token delivery; tables are sandboxed.
111
- - **Single-use + server-sourced time** — terminal states are final (no double-grant); TTL is enforced on read; timestamps come from `Date.now()`, never the caller.
112
- - **Opaque host data** — `resourceRef`/`role`/`payload` are opaque, narrowed only by the optional host validators at the client boundary.
301
+ ```ts
302
+ // convex/convex.config.ts
303
+ import invitations from "@vllnt/convex-invitations/convex.config";
304
+ import { defineApp } from "convex/server";
113
305
 
114
- See [docs/API.md](docs/API.md).
306
+ const app = defineApp();
307
+ app.use(invitations);
308
+ app.use(invitations, { name: "guestInvites" });
309
+ export default app;
310
+ ```
311
+
312
+ ```ts
313
+ // convex/clients.ts
314
+ import { Invitations } from "@vllnt/convex-invitations";
315
+
316
+ import { components } from "./_generated/api";
317
+
318
+ export const teamInvites = new Invitations(components.invitations);
319
+ export const guestInvites = new Invitations(components.guestInvites, {
320
+ ttlMs: 24 * 60 * 60 * 1000,
321
+ });
322
+ ```
323
+
324
+ ## Errors and fixes
325
+
326
+ Every component error is a `ConvexError` whose `data` is `{ code, message }`.
327
+ Catch it in the host with `error instanceof ConvexError` and read
328
+ `error.data.code`.
329
+
330
+ | Code | Thrown by | Cause | Fix |
331
+ | ------------------ | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
332
+ | `INVALID_TOKEN` | `issue`, `accept`, `revoke`, `peek` | The token is empty or longer than 512 characters (for `issue`: what `generateToken` returned) | Pass the token exactly as `issue` returned it; keep custom tokens 1 to 512 characters |
333
+ | `INVALID_ARGUMENT` | `issue`, `accept`, `prune` | Empty `resourceRef`, `inviterRef`, `inviteeRef` or `acceptedBy`; `expiresAt` not finite or not in the future (also a zero, negative or `NaN` `ttlMs`); `NaN` `before` or `retentionBefore` | Pass non-empty refs (omit optional ones instead of `""`), a positive `ttlMs` or a future `expiresAt` |
334
+ | `INVALID_BATCH` | `prune`, `migrateLegacyTokens` | `batch` is not an integer from 1 to 500 (`prune`) or 1 to 100 (`migrateLegacyTokens`) | Omit `batch` (defaults 200 and 50) or pass an integer in range |
335
+ | `DUPLICATE_TOKEN` | `issue` | `generateToken` returned a token that an existing invite already uses | Use an unpredictable generator such as the default `crypto.randomUUID` |
336
+ | `NOT_FOUND` | `accept`, `revoke` | No invite has this token (never issued, mistyped, or already deleted by `prune`) | Show "invalid link"; `peek` and `getByToken` return `null` for the same case |
337
+ | `EXPIRED` | `accept` | The invite is still `pending` but `expiresAt` has passed | Ask the inviter to issue a new invite |
338
+ | `ALREADY_ACCEPTED` | `accept`, `revoke` | The invite was already accepted (single use) | Treat a repeat accept by the same user as done; otherwise issue a new invite |
339
+ | `ALREADY_REVOKED` | `accept`, `revoke` | The invite was revoked | Issue a new invite |
340
+ | `ALREADY_EXPIRED` | `accept`, `revoke` | The invite's state was already set to `expired` by `peek` or `prune` | Issue a new invite |
341
+
342
+ Arguments of the wrong type are rejected by Convex argument validation before
343
+ the component runs. An error thrown by your `roleValidator` or
344
+ `payloadValidator` is your own error and reaches the caller unchanged.
345
+
346
+ ## Limits and gotchas
347
+
348
+ - Tokens are 1 to 512 characters (JavaScript string length). The default
349
+ `generateToken` is `crypto.randomUUID()` (36 characters).
350
+ - New rows store only a SHA-256 digest of the token; older rows keep their raw
351
+ token until `migrateLegacyTokens` or the daily cron hashes it. `issue`
352
+ returns the raw token once; `peek` and `getByToken` echo the token you pass
353
+ in, and the list queries return no token at all. Nothing can recover a lost
354
+ token.
355
+ - `getByToken`, `listPending` and `listByResourceState` report the stored
356
+ state: an invite past `expiresAt` reads `pending` until `peek` or the daily
357
+ cron stores `expired`. `accept` rejects it with `EXPIRED` but does not store
358
+ the change, because a throwing mutation rolls back its writes.
359
+ - `revoke` does not check `expiresAt`: a past-TTL invite still stored as
360
+ `pending` becomes `revoked`.
361
+ - `accept` checks the state before the expiry, so a stored `expired` invite
362
+ throws `ALREADY_EXPIRED`, and a stale `pending` one throws `EXPIRED`.
363
+ - `inviteeRef` is stored metadata only. `accept` does not compare it with
364
+ `acceptedBy`; check the recipient yourself before calling `accept`.
365
+ - Default TTL is 7 days. `IssueOptions.expiresAt` wins over `ttlMs`, which wins
366
+ over the client's `ttlMs`.
367
+ - Retention is 30 days counted from `createdAt`, not from acceptance or
368
+ revocation. The built-in cron deletes accepted, revoked and expired invites
369
+ older than that, so copy anything you must keep longer into your own table.
370
+ - Calling `prune` yourself does not change the built-in cron, which runs every
371
+ 24 hours with batch 200 and the default cutoffs. Each pass deletes and
372
+ expires at most `batch` rows and schedules another pass when it used the whole
373
+ batch. `prune` returns the count of the first pass only.
374
+ - `prune` `batch` is an integer from 1 to 500 (default 200).
375
+ `migrateLegacyTokens` `batch` is an integer from 1 to 100 (default 50).
376
+ `before` and `retentionBefore` accept `Infinity` but not `NaN`.
377
+ - List pages are ordered oldest first by `createdAt`. Page size comes from
378
+ `paginationOpts.numItems`; the component adds no limit of its own.
379
+ - `role` and `payload` are stored as any Convex value. Your validators run on
380
+ write and on every read, so a validator that rejects older stored values
381
+ makes those reads throw.
382
+ - `accept` returns the grant; it writes nothing in your tables. Call it from a
383
+ mutation and apply the grant in that same mutation. Called from an action,
384
+ the accept and your write are separate transactions.
385
+ - Mutation-only methods (`issue`, `accept`, `revoke`, `peek`,
386
+ `migrateLegacyTokens`, `prune`) need a `ctx` with `runMutation`; they cannot
387
+ run in a query.
388
+ - The component sends nothing and reads no auth. Delivery, identity and
389
+ permission checks belong to the host.
390
+
391
+ ## Compatibility
392
+
393
+ - Peer dependency: `convex@^1.45.0`. This repository's unit tests run on the
394
+ locked convex version; `pnpm test:package` type-checks the README examples
395
+ and runs the Testing example against convex 1.45.0.
396
+ - Node.js: what your convex version needs. convex 1.45 to 1.48 declare
397
+ `node >=20.0.0`; convex 1.49 and newer declare `node >=22.0.0`.
398
+ - Convex runtime: the component and the client use only the default Convex
399
+ runtime (no Node.js actions). Named mounts with `app.use(invitations, { name })`
400
+ are supported.
401
+ - ES modules only.
402
+ - `@vllnt/convex-invitations/test` needs `convex-test`, `vitest`, `vite` and
403
+ `@edge-runtime/vm`. Add `vite` as a direct dev dependency: the
404
+ `vite/client` types the helper references come from it.
405
+ - React: not applicable. The package is backend-only and has no `./react` entry;
406
+ use `useQuery` on your own wrappers of `getByToken` or `listPending`.
115
407
 
116
408
  ## Testing
117
409
 
118
- ```bash
119
- pnpm test # single run
120
- pnpm test:coverage # enforced 100% on covered files
410
+ Mount the component in your own `convex-test` suite with `register(t)` from
411
+ `@vllnt/convex-invitations/test`. `t` can be built from your host schema. Use the
412
+ Vitest settings `convex-test` recommends:
413
+
414
+ ```ts
415
+ // vitest.config.mts
416
+ import { defineConfig } from "vitest/config";
417
+
418
+ export default defineConfig({
419
+ test: {
420
+ environment: "edge-runtime",
421
+ server: { deps: { inline: ["convex-test"] } },
422
+ },
423
+ });
121
424
  ```
122
425
 
123
- Tests run against the real component runtime via `convex-test` (`@edge-runtime/vm`), not mocks.
426
+ ```ts
427
+ // convex/invites.test.ts
428
+ /// <reference types="vite/client" />
429
+ import { register } from "@vllnt/convex-invitations/test";
430
+ import { convexTest } from "convex-test";
431
+ import { expect, test } from "vitest";
432
+
433
+ import { api } from "./_generated/api";
434
+ import schema from "./schema";
435
+
436
+ test("an invite works once", async () => {
437
+ const t = convexTest(schema, import.meta.glob("./**/*.ts"));
438
+ register(t);
439
+ const owner = t.withIdentity({ tokenIdentifier: "owner" });
440
+ const guest = t.withIdentity({ tokenIdentifier: "guest" });
441
+ const { token } = await owner.mutation(api.invites.createInvite, {
442
+ orgId: "org_1",
443
+ role: "member",
444
+ });
445
+ const joined = await guest.mutation(api.invites.acceptInvite, { token });
446
+ expect(joined).toEqual({ orgId: "org_1", role: "member" });
447
+ await expect(
448
+ guest.mutation(api.invites.acceptInvite, { token }),
449
+ ).rejects.toThrow(/ALREADY_ACCEPTED/u);
450
+ });
451
+ ```
124
452
 
125
- ## Contributing
453
+ `register(t, name)` takes the mount name when you used
454
+ `app.use(invitations, { name })`.
455
+
456
+ This repository's own tests run on the simulated `convex-test` runtime, not
457
+ mocks: `pnpm test:coverage` (100% coverage enforced).
458
+
459
+ ## Security
126
460
 
127
- See [CONTRIBUTING.md](CONTRIBUTING.md).
461
+ - The component does not authenticate. The host authorizes every call and
462
+ derives `inviterRef`, `acceptedBy` and the resource from its own auth; never
463
+ take `acceptedBy` from the client.
464
+ - Tokens are bearer secrets: anyone holding the link can accept it. Keep them
465
+ out of logs and analytics, deliver them over a secure channel, and keep a
466
+ custom `generateToken` unpredictable. Hashing at rest does not protect a
467
+ leaked link.
468
+ - Terminal states are final and every transition is one check-and-patch in one
469
+ mutation, so racing accepts or an accept racing a revoke have one winner.
470
+ - `createdAt`, `acceptedAt` and `revokedAt` come from the server clock.
471
+ - The `invitations` table is reachable only through the component's functions.
128
472
 
129
- ## Author
473
+ Report vulnerabilities as described in
474
+ [SECURITY.md](https://github.com/vllnt/convex-invitations/blob/main/SECURITY.md).
130
475
 
131
- Built by [bntvllnt](https://github.com/bntvllnt) · [bntvllnt.com](https://bntvllnt.com) · [X @bntvllnt](https://x.com/bntvllnt)
476
+ ## Related packages
132
477
 
133
- Part of the [@vllnt](https://github.com/vllnt) Convex component fleet — [vllnt.com](https://vllnt.com)
478
+ No other `@vllnt` package is used with this one in code.
134
479
 
135
- If this is useful, [sponsor the work](https://github.com/sponsors/bntvllnt).
480
+ ## Contributing
481
+
482
+ See
483
+ [CONTRIBUTING.md](https://github.com/vllnt/convex-invitations/blob/main/CONTRIBUTING.md).
484
+
485
+ ## Links
486
+
487
+ - Docs and changelog: [oss.vllnt.com/packages/convex-invitations](https://oss.vllnt.com/packages/convex-invitations) · [release feed](https://oss.vllnt.com/packages/convex-invitations/rss.xml)
488
+ - All @vllnt packages: [oss.vllnt.com](https://oss.vllnt.com) · [search packages and docs on index.vllnt.com](https://index.vllnt.com)
489
+ - Source and issues: [GitHub](https://github.com/vllnt/convex-invitations) · [issues](https://github.com/vllnt/convex-invitations/issues) · [npm](https://www.npmjs.com/package/@vllnt/convex-invitations)
490
+ - Questions and updates: [Discord](https://bntvllnt.com/discord) · [X @bntvllnt](https://x.com/bntvllnt)
491
+ - Company and author: [vllnt.com](https://vllnt.com) · [bntvllnt.com](https://bntvllnt.com) · [GitHub @bntvllnt](https://github.com/bntvllnt) · [LinkedIn](https://linkedin.com/in/bntvllnt)
492
+ - Sponsor: [GitHub Sponsors](https://github.com/sponsors/bntvllnt)
136
493
 
137
494
  ## License
138
495
 
139
- MIT — see [LICENSE](LICENSE).
496
+ MIT. See [LICENSE](LICENSE).
497
+
498
+ [![npm version](https://img.shields.io/npm/v/@vllnt/convex-invitations.svg)](https://www.npmjs.com/package/@vllnt/convex-invitations)
499
+ [![CI status](https://github.com/vllnt/convex-invitations/actions/workflows/ci.yml/badge.svg)](https://github.com/vllnt/convex-invitations/actions/workflows/ci.yml)
500
+
501
+ ---
502
+
503
+ Part of [vllnt open source](https://oss.vllnt.com) · [Package page](https://oss.vllnt.com/packages/convex-invitations) · [vllnt.com](https://vllnt.com) · Built by [bntvllnt](https://bntvllnt.com)
@@ -101,11 +101,8 @@ interface RunMutationCtx {
101
101
  * `roleValidator` / `payloadValidator` to narrow that opaque data to
102
102
  * `TRole` / `TPayload` at the boundary — there is no unchecked cast.
103
103
  *
104
- * Invitation state is self-contained, but only a SHA-256 token digest is persisted;
105
- * the raw bearer token is returned once by `issue`. A later version could delegate
106
- * the hashed/revocable token to
107
- * `@vllnt/convex-tokens` and write the granted membership via
108
- * `@vllnt/convex-memberships`, with `accept` composing the two.
104
+ * Only a SHA-256 digest of each token is stored; `issue` returns the raw bearer
105
+ * token once, and no method can recover it later.
109
106
  *
110
107
  * @typeParam TRole - The host's role type to grant on accept (defaults to `unknown`).
111
108
  * @typeParam TPayload - The host's opaque invite payload type (defaults to `unknown`).
@@ -114,13 +111,18 @@ interface RunMutationCtx {
114
111
  * ```ts
115
112
  * const invites = new Invitations(components.invitations, {
116
113
  * ttlMs: 1000 * 60 * 60 * 24 * 3, // 3-day links
117
- * roleValidator: v.union(v.literal("admin"), v.literal("member")).parse,
114
+ * roleValidator: (value) => {
115
+ * if (value !== "admin" && value !== "member") throw new Error("Invalid role");
116
+ * return value;
117
+ * },
118
118
  * });
119
119
  * const { token } = await invites.issue(ctx, "org_42", { role: "member", inviterRef: me });
120
120
  * // ... invitee later redeems the link:
121
121
  * const grant = await invites.accept(ctx, token, invitee);
122
122
  * // host applies grant.resourceRef + grant.role (writes a membership)
123
123
  * ```
124
+ *
125
+ * @see https://oss.vllnt.com/packages/convex-invitations
124
126
  */
125
127
  export declare class Invitations<TRole = unknown, TPayload = unknown> {
126
128
  private readonly component;
@@ -184,7 +186,7 @@ export declare class Invitations<TRole = unknown, TPayload = unknown> {
184
186
  /**
185
187
  * The current view of one invitation by its `token`, or `null` — a pure
186
188
  * reactive read (no write). Reports the stored `state` as-is, so a past-TTL
187
- * invite may still read `pending` until a `peek`/`accept`/cron sweep flips it;
189
+ * invite may still read `pending` until a `peek`/cron sweep flips it;
188
190
  * compare `expiresAt` against the clock, or use {@link peek} for read-time TTL.
189
191
  */
190
192
  getByToken(ctx: RunQueryCtx, token: string): Promise<InvitationView<TRole, TPayload> | null>;