@vllnt/convex-invitations 0.1.0-canary.01d468e
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/LICENSE +21 -0
- package/README.md +139 -0
- package/dist/client/index.d.ts +196 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +181 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/types.d.ts +93 -0
- package/dist/client/types.d.ts.map +1 -0
- package/dist/client/types.js +3 -0
- package/dist/client/types.js.map +1 -0
- package/dist/component/_generated/api.d.ts +40 -0
- package/dist/component/_generated/api.d.ts.map +1 -0
- package/dist/component/_generated/api.js +31 -0
- package/dist/component/_generated/api.js.map +1 -0
- package/dist/component/_generated/component.d.ts +148 -0
- package/dist/component/_generated/component.d.ts.map +1 -0
- package/dist/component/_generated/component.js +11 -0
- package/dist/component/_generated/component.js.map +1 -0
- package/dist/component/_generated/dataModel.d.ts +46 -0
- package/dist/component/_generated/dataModel.d.ts.map +1 -0
- package/dist/component/_generated/dataModel.js +11 -0
- package/dist/component/_generated/dataModel.js.map +1 -0
- package/dist/component/_generated/server.d.ts +133 -0
- package/dist/component/_generated/server.d.ts.map +1 -0
- package/dist/component/_generated/server.js +80 -0
- package/dist/component/_generated/server.js.map +1 -0
- package/dist/component/convex.config.d.ts +3 -0
- package/dist/component/convex.config.d.ts.map +1 -0
- package/dist/component/convex.config.js +7 -0
- package/dist/component/convex.config.js.map +1 -0
- package/dist/component/crons.d.ts +19 -0
- package/dist/component/crons.d.ts.map +1 -0
- package/dist/component/crons.js +22 -0
- package/dist/component/crons.js.map +1 -0
- package/dist/component/mutations.d.ts +118 -0
- package/dist/component/mutations.d.ts.map +1 -0
- package/dist/component/mutations.js +272 -0
- package/dist/component/mutations.js.map +1 -0
- package/dist/component/queries.d.ts +98 -0
- package/dist/component/queries.d.ts.map +1 -0
- package/dist/component/queries.js +93 -0
- package/dist/component/queries.js.map +1 -0
- package/dist/component/schema.d.ts +56 -0
- package/dist/component/schema.d.ts.map +1 -0
- package/dist/component/schema.js +44 -0
- package/dist/component/schema.js.map +1 -0
- package/dist/component/validators.d.ts +49 -0
- package/dist/component/validators.d.ts.map +1 -0
- package/dist/component/validators.js +37 -0
- package/dist/component/validators.js.map +1 -0
- package/dist/shared.d.ts +33 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +40 -0
- package/dist/shared.js.map +1 -0
- package/package.json +101 -0
- package/src/client/index.ts +357 -0
- package/src/client/types.ts +98 -0
- package/src/component/_generated/api.ts +56 -0
- package/src/component/_generated/component.ts +179 -0
- package/src/component/_generated/dataModel.ts +60 -0
- package/src/component/_generated/server.ts +169 -0
- package/src/component/convex.config.ts +9 -0
- package/src/component/crons.ts +26 -0
- package/src/component/mutations.ts +307 -0
- package/src/component/queries.ts +113 -0
- package/src/component/schema.ts +44 -0
- package/src/component/validators.ts +44 -0
- package/src/shared.ts +48 -0
- package/src/test.ts +12 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
/**
|
|
3
|
+
* Generated data model types.
|
|
4
|
+
*
|
|
5
|
+
* THIS CODE IS AUTOMATICALLY GENERATED.
|
|
6
|
+
*
|
|
7
|
+
* To regenerate, run `npx convex dev`.
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type {
|
|
12
|
+
DataModelFromSchemaDefinition,
|
|
13
|
+
DocumentByName,
|
|
14
|
+
TableNamesInDataModel,
|
|
15
|
+
SystemTableNames,
|
|
16
|
+
} from "convex/server";
|
|
17
|
+
import type { GenericId } from "convex/values";
|
|
18
|
+
import schema from "../schema.js";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The names of all of your Convex tables.
|
|
22
|
+
*/
|
|
23
|
+
export type TableNames = TableNamesInDataModel<DataModel>;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The type of a document stored in Convex.
|
|
27
|
+
*
|
|
28
|
+
* @typeParam TableName - A string literal type of the table name (like "users").
|
|
29
|
+
*/
|
|
30
|
+
export type Doc<TableName extends TableNames> = DocumentByName<
|
|
31
|
+
DataModel,
|
|
32
|
+
TableName
|
|
33
|
+
>;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* An identifier for a document in Convex.
|
|
37
|
+
*
|
|
38
|
+
* Convex documents are uniquely identified by their `Id`, which is accessible
|
|
39
|
+
* on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
|
|
40
|
+
*
|
|
41
|
+
* Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
|
|
42
|
+
*
|
|
43
|
+
* IDs are just strings at runtime, but this type can be used to distinguish them from other
|
|
44
|
+
* strings when type checking.
|
|
45
|
+
*
|
|
46
|
+
* @typeParam TableName - A string literal type of the table name (like "users").
|
|
47
|
+
*/
|
|
48
|
+
export type Id<TableName extends TableNames | SystemTableNames> =
|
|
49
|
+
GenericId<TableName>;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* A type describing your Convex data model.
|
|
53
|
+
*
|
|
54
|
+
* This type includes information about what tables you have, the type of
|
|
55
|
+
* documents stored in those tables, and the indexes defined on them.
|
|
56
|
+
*
|
|
57
|
+
* This type is used to parameterize methods like `queryGeneric` and
|
|
58
|
+
* `mutationGeneric` to make them type-safe.
|
|
59
|
+
*/
|
|
60
|
+
export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
/**
|
|
3
|
+
* Generated utilities for implementing server-side Convex query and mutation functions.
|
|
4
|
+
*
|
|
5
|
+
* THIS CODE IS AUTOMATICALLY GENERATED.
|
|
6
|
+
*
|
|
7
|
+
* To regenerate, run `npx convex dev`.
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type {
|
|
12
|
+
ActionBuilder,
|
|
13
|
+
HttpActionBuilder,
|
|
14
|
+
MutationBuilder,
|
|
15
|
+
QueryBuilder,
|
|
16
|
+
GenericActionCtx,
|
|
17
|
+
GenericMutationCtx,
|
|
18
|
+
GenericQueryCtx,
|
|
19
|
+
GenericDatabaseReader,
|
|
20
|
+
GenericDatabaseWriter,
|
|
21
|
+
} from "convex/server";
|
|
22
|
+
import {
|
|
23
|
+
actionGeneric,
|
|
24
|
+
httpActionGeneric,
|
|
25
|
+
queryGeneric,
|
|
26
|
+
mutationGeneric,
|
|
27
|
+
internalActionGeneric,
|
|
28
|
+
internalMutationGeneric,
|
|
29
|
+
internalQueryGeneric,
|
|
30
|
+
} from "convex/server";
|
|
31
|
+
import type { DataModel } from "./dataModel.js";
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Typesafe environment variables.
|
|
35
|
+
*
|
|
36
|
+
* This includes platform-provided env vars and any variables declared in
|
|
37
|
+
* `convex.config.ts`.
|
|
38
|
+
*/
|
|
39
|
+
type Env = {
|
|
40
|
+
readonly CONVEX_CLOUD_URL: string;
|
|
41
|
+
readonly CONVEX_SITE_URL: string;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Define a query in this Convex app's public API.
|
|
46
|
+
*
|
|
47
|
+
* This function will be allowed to read your Convex database and will be accessible from the client.
|
|
48
|
+
*
|
|
49
|
+
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
|
|
50
|
+
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
|
|
51
|
+
*/
|
|
52
|
+
export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Define a query that is only accessible from other Convex functions (but not from the client).
|
|
56
|
+
*
|
|
57
|
+
* This function will be allowed to read from your Convex database. It will not be accessible from the client.
|
|
58
|
+
*
|
|
59
|
+
* @param func - The query function. It receives a {@link QueryCtx} as its first argument.
|
|
60
|
+
* @returns The wrapped query. Include this as an `export` to name it and make it accessible.
|
|
61
|
+
*/
|
|
62
|
+
export const internalQuery: QueryBuilder<DataModel, "internal"> =
|
|
63
|
+
internalQueryGeneric;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Define a mutation in this Convex app's public API.
|
|
67
|
+
*
|
|
68
|
+
* This function will be allowed to modify your Convex database and will be accessible from the client.
|
|
69
|
+
*
|
|
70
|
+
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
|
|
71
|
+
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
|
|
72
|
+
*/
|
|
73
|
+
export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Define a mutation that is only accessible from other Convex functions (but not from the client).
|
|
77
|
+
*
|
|
78
|
+
* This function will be allowed to modify your Convex database. It will not be accessible from the client.
|
|
79
|
+
*
|
|
80
|
+
* @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
|
|
81
|
+
* @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
|
|
82
|
+
*/
|
|
83
|
+
export const internalMutation: MutationBuilder<DataModel, "internal"> =
|
|
84
|
+
internalMutationGeneric;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Define an action in this Convex app's public API.
|
|
88
|
+
*
|
|
89
|
+
* An action is a function which can execute any JavaScript code, including non-deterministic
|
|
90
|
+
* code and code with side-effects, like calling third-party services.
|
|
91
|
+
* They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
|
|
92
|
+
* They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
|
|
93
|
+
*
|
|
94
|
+
* @param func - The action. It receives an {@link ActionCtx} as its first argument.
|
|
95
|
+
* @returns The wrapped action. Include this as an `export` to name it and make it accessible.
|
|
96
|
+
*/
|
|
97
|
+
export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Define an action that is only accessible from other Convex functions (but not from the client).
|
|
101
|
+
*
|
|
102
|
+
* @param func - The function. It receives an {@link ActionCtx} as its first argument.
|
|
103
|
+
* @returns The wrapped function. Include this as an `export` to name it and make it accessible.
|
|
104
|
+
*/
|
|
105
|
+
export const internalAction: ActionBuilder<DataModel, "internal"> =
|
|
106
|
+
internalActionGeneric;
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Define an HTTP action.
|
|
110
|
+
*
|
|
111
|
+
* The wrapped function will be used to respond to HTTP requests received
|
|
112
|
+
* by a Convex deployment if the requests matches the path and method where
|
|
113
|
+
* this action is routed. Be sure to route your httpAction in `convex/http.js`.
|
|
114
|
+
*
|
|
115
|
+
* @param func - The function. It receives an {@link ActionCtx} as its first argument
|
|
116
|
+
* and a Fetch API `Request` object as its second.
|
|
117
|
+
* @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
|
|
118
|
+
*/
|
|
119
|
+
export const httpAction: HttpActionBuilder = httpActionGeneric;
|
|
120
|
+
export const env: Env = (globalThis as unknown as { process: { env: Env } })
|
|
121
|
+
.process.env;
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* A set of services for use within Convex query functions.
|
|
125
|
+
*
|
|
126
|
+
* The query context is passed as the first argument to any Convex query
|
|
127
|
+
* function run on the server.
|
|
128
|
+
*
|
|
129
|
+
* If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
|
|
130
|
+
*/
|
|
131
|
+
export type QueryCtx = GenericQueryCtx<DataModel>;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* A set of services for use within Convex mutation functions.
|
|
135
|
+
*
|
|
136
|
+
* The mutation context is passed as the first argument to any Convex mutation
|
|
137
|
+
* function run on the server.
|
|
138
|
+
*
|
|
139
|
+
* If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
|
|
140
|
+
*/
|
|
141
|
+
export type MutationCtx = GenericMutationCtx<DataModel>;
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* A set of services for use within Convex action functions.
|
|
145
|
+
*
|
|
146
|
+
* The action context is passed as the first argument to any Convex action
|
|
147
|
+
* function run on the server.
|
|
148
|
+
*/
|
|
149
|
+
export type ActionCtx = GenericActionCtx<DataModel>;
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* An interface to read from the database within Convex query functions.
|
|
153
|
+
*
|
|
154
|
+
* The two entry points are {@link DatabaseReader.get}, which fetches a single
|
|
155
|
+
* document by its {@link Id}, or {@link DatabaseReader.query}, which starts
|
|
156
|
+
* building a query.
|
|
157
|
+
*/
|
|
158
|
+
export type DatabaseReader = GenericDatabaseReader<DataModel>;
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* An interface to read from and write to the database within Convex mutation
|
|
162
|
+
* functions.
|
|
163
|
+
*
|
|
164
|
+
* Convex guarantees that all writes within a single mutation are
|
|
165
|
+
* executed atomically, so you never have to worry about partial writes leaving
|
|
166
|
+
* your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
|
|
167
|
+
* for the guarantees Convex provides your functions.
|
|
168
|
+
*/
|
|
169
|
+
export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { defineComponent } from "convex/server";
|
|
2
|
+
|
|
3
|
+
const component = defineComponent("invitations");
|
|
4
|
+
|
|
5
|
+
// Nest official child components here, e.g.:
|
|
6
|
+
// import sharded from "@convex-dev/sharded-counter/convex.config";
|
|
7
|
+
// component.use(sharded);
|
|
8
|
+
|
|
9
|
+
export default component;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { cronJobs } from "convex/server";
|
|
2
|
+
import { api } from "./_generated/api";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Default sweep cadence and page size for the built-in prune cron. The cron is
|
|
6
|
+
* the component's own self-healing safety net — it expires stale `pending`
|
|
7
|
+
* invites (so a never-accepted invite does not linger open forever) and deletes
|
|
8
|
+
* terminal invites past retention. A host that wants a different cadence drives
|
|
9
|
+
* `prune` from its own scheduler instead (the client exposes it).
|
|
10
|
+
*
|
|
11
|
+
* Convex cron definitions are static per deployment, so cadence is a documented
|
|
12
|
+
* module constant rather than a mount-time option; the page size bounds each
|
|
13
|
+
* sweep and `prune` self-reschedules until the tail is clean.
|
|
14
|
+
*/
|
|
15
|
+
export const PRUNE_INTERVAL = { hours: 24 } as const;
|
|
16
|
+
|
|
17
|
+
/** Rows touched per `prune` pass before the sweep self-reschedules. */
|
|
18
|
+
export const PRUNE_BATCH = 200;
|
|
19
|
+
|
|
20
|
+
const crons = cronJobs();
|
|
21
|
+
|
|
22
|
+
crons.interval("invitations:prune", PRUNE_INTERVAL, api.mutations.prune, {
|
|
23
|
+
batch: PRUNE_BATCH,
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
export default crons;
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { ConvexError, v } from "convex/values";
|
|
2
|
+
import { api } from "./_generated/api";
|
|
3
|
+
import { mutation } from "./_generated/server";
|
|
4
|
+
import { invitationView, jsonValue } from "./validators";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Issue an invitation to a `resourceRef` and return the single-use `token` the
|
|
8
|
+
* host hands to the invitee (out of band — an email, a link). The invite is
|
|
9
|
+
* inserted `pending` with `createdAt` stamped from the server clock and
|
|
10
|
+
* `expiresAt` set from the caller-resolved TTL (the client computes it from
|
|
11
|
+
* `ttlMs` or passes an absolute `expiresAt`).
|
|
12
|
+
*
|
|
13
|
+
* `token` is host-supplied (the client mints a random one) and must be unique —
|
|
14
|
+
* re-using an existing token throws
|
|
15
|
+
* `ConvexError({ code: "DUPLICATE_TOKEN" })` so a collision can never clobber an
|
|
16
|
+
* open invite. `resourceRef`, `role`, `inviterRef`, `inviteeRef`, and `payload`
|
|
17
|
+
* are opaque host data carried through to acceptance; the component never
|
|
18
|
+
* inspects them.
|
|
19
|
+
*/
|
|
20
|
+
export const issue = mutation({
|
|
21
|
+
args: {
|
|
22
|
+
token: v.string(),
|
|
23
|
+
resourceRef: v.string(),
|
|
24
|
+
role: v.optional(jsonValue),
|
|
25
|
+
inviterRef: v.optional(v.string()),
|
|
26
|
+
inviteeRef: v.optional(v.string()),
|
|
27
|
+
payload: v.optional(jsonValue),
|
|
28
|
+
expiresAt: v.number(),
|
|
29
|
+
},
|
|
30
|
+
returns: v.object({ token: v.string(), expiresAt: v.number() }),
|
|
31
|
+
handler: async (ctx, args) => {
|
|
32
|
+
const existing = await ctx.db
|
|
33
|
+
.query("invitations")
|
|
34
|
+
.withIndex("by_token", (q) => q.eq("token", args.token))
|
|
35
|
+
.unique();
|
|
36
|
+
if (existing !== null) {
|
|
37
|
+
throw new ConvexError({
|
|
38
|
+
code: "DUPLICATE_TOKEN",
|
|
39
|
+
message: `invitation token already exists`,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
await ctx.db.insert("invitations", {
|
|
44
|
+
token: args.token,
|
|
45
|
+
resourceRef: args.resourceRef,
|
|
46
|
+
role: args.role,
|
|
47
|
+
inviterRef: args.inviterRef,
|
|
48
|
+
inviteeRef: args.inviteeRef,
|
|
49
|
+
payload: args.payload,
|
|
50
|
+
state: "pending",
|
|
51
|
+
createdAt: Date.now(),
|
|
52
|
+
expiresAt: args.expiresAt,
|
|
53
|
+
});
|
|
54
|
+
return { token: args.token, expiresAt: args.expiresAt };
|
|
55
|
+
},
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Redeem an invitation by its `token` — the single-use accept transaction.
|
|
60
|
+
* Atomically: the invite must exist, be `pending`, and not be past its
|
|
61
|
+
* `expiresAt` as of the server clock. On success it transitions to `accepted`
|
|
62
|
+
* (recording `acceptedAt` and the opaque `acceptedBy` subject) and returns the
|
|
63
|
+
* grant the host applies — `resourceRef` + opaque `role`/`payload`. Because the
|
|
64
|
+
* single check-and-patch runs in one mutation, two racing accepts yield exactly
|
|
65
|
+
* one winner: the second sees a non-`pending` invite and is rejected.
|
|
66
|
+
*
|
|
67
|
+
* A `pending` invite found past its TTL is rejected with `EXPIRED` but NOT
|
|
68
|
+
* flipped here — a thrown mutation rolls back its own writes, so the flip would
|
|
69
|
+
* not persist. The non-throwing `peek` mutation and the prune cron sweep
|
|
70
|
+
* `pending → expired` instead; the TTL is still enforced on read (the stale
|
|
71
|
+
* invite can never be accepted).
|
|
72
|
+
*
|
|
73
|
+
* @throws `ConvexError({ code: "NOT_FOUND" })` when no invitation has `token`.
|
|
74
|
+
* @throws `ConvexError({ code: "EXPIRED" })` when the invite's TTL has elapsed.
|
|
75
|
+
* @throws `ConvexError({ code: "ALREADY_<STATE>" })` when the invite was already
|
|
76
|
+
* accepted, revoked, or expired (single-use — a terminal invite cannot be
|
|
77
|
+
* redeemed again).
|
|
78
|
+
*/
|
|
79
|
+
export const accept = mutation({
|
|
80
|
+
args: { token: v.string(), acceptedBy: v.string() },
|
|
81
|
+
returns: v.object({
|
|
82
|
+
resourceRef: v.string(),
|
|
83
|
+
role: v.optional(jsonValue),
|
|
84
|
+
payload: v.optional(jsonValue),
|
|
85
|
+
}),
|
|
86
|
+
handler: async (ctx, args) => {
|
|
87
|
+
const invite = await ctx.db
|
|
88
|
+
.query("invitations")
|
|
89
|
+
.withIndex("by_token", (q) => q.eq("token", args.token))
|
|
90
|
+
.unique();
|
|
91
|
+
if (invite === null) {
|
|
92
|
+
throw new ConvexError({
|
|
93
|
+
code: "NOT_FOUND",
|
|
94
|
+
message: `invitation not found`,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
if (invite.state !== "pending") {
|
|
98
|
+
throw new ConvexError({
|
|
99
|
+
code: `ALREADY_${invite.state.toUpperCase()}`,
|
|
100
|
+
message: `invitation is already ${invite.state} and cannot be accepted`,
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const now = Date.now();
|
|
105
|
+
if (invite.expiresAt <= now) {
|
|
106
|
+
throw new ConvexError({
|
|
107
|
+
code: "EXPIRED",
|
|
108
|
+
message: `invitation expired`,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
await ctx.db.patch("invitations", invite._id, {
|
|
113
|
+
state: "accepted",
|
|
114
|
+
acceptedAt: now,
|
|
115
|
+
acceptedBy: args.acceptedBy,
|
|
116
|
+
});
|
|
117
|
+
return {
|
|
118
|
+
resourceRef: invite.resourceRef,
|
|
119
|
+
role: invite.role,
|
|
120
|
+
payload: invite.payload,
|
|
121
|
+
};
|
|
122
|
+
},
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Revoke a still-`pending` invitation by its `token`, transitioning it to
|
|
127
|
+
* `revoked` (recording `revokedAt`). A revoked invite can never be accepted.
|
|
128
|
+
* Already-terminal invites are rejected — revoking is itself a single
|
|
129
|
+
* `pending → revoked` transition, so a revoke racing an accept yields one
|
|
130
|
+
* winner.
|
|
131
|
+
*
|
|
132
|
+
* @throws `ConvexError({ code: "NOT_FOUND" })` when no invitation has `token`.
|
|
133
|
+
* @throws `ConvexError({ code: "ALREADY_<STATE>" })` when the invite is already
|
|
134
|
+
* accepted, revoked, or expired.
|
|
135
|
+
*/
|
|
136
|
+
export const revoke = mutation({
|
|
137
|
+
args: { token: v.string() },
|
|
138
|
+
returns: v.null(),
|
|
139
|
+
handler: async (ctx, args) => {
|
|
140
|
+
const invite = await ctx.db
|
|
141
|
+
.query("invitations")
|
|
142
|
+
.withIndex("by_token", (q) => q.eq("token", args.token))
|
|
143
|
+
.unique();
|
|
144
|
+
if (invite === null) {
|
|
145
|
+
throw new ConvexError({
|
|
146
|
+
code: "NOT_FOUND",
|
|
147
|
+
message: `invitation not found`,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
if (invite.state !== "pending") {
|
|
151
|
+
throw new ConvexError({
|
|
152
|
+
code: `ALREADY_${invite.state.toUpperCase()}`,
|
|
153
|
+
message: `invitation is already ${invite.state} and cannot be revoked`,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
await ctx.db.patch("invitations", invite._id, { state: "revoked", revokedAt: Date.now() });
|
|
157
|
+
return null;
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The current view of one invitation by its `token`, or `null` if no such
|
|
163
|
+
* invite is held. Lives in `mutations.ts` (not `queries.ts`) because it flips a
|
|
164
|
+
* `pending` invite found past its TTL to `expired` before returning — the same
|
|
165
|
+
* read-time TTL enforcement `accept` does, so a status check never reports a
|
|
166
|
+
* stale invite as still open.
|
|
167
|
+
*/
|
|
168
|
+
export const peek = mutation({
|
|
169
|
+
args: { token: v.string() },
|
|
170
|
+
returns: v.union(v.null(), invitationView),
|
|
171
|
+
handler: async (ctx, args) => {
|
|
172
|
+
const invite = await ctx.db
|
|
173
|
+
.query("invitations")
|
|
174
|
+
.withIndex("by_token", (q) => q.eq("token", args.token))
|
|
175
|
+
.unique();
|
|
176
|
+
if (invite === null) {
|
|
177
|
+
return null;
|
|
178
|
+
}
|
|
179
|
+
if (invite.state === "pending" && invite.expiresAt <= Date.now()) {
|
|
180
|
+
await ctx.db.patch("invitations", invite._id, { state: "expired" });
|
|
181
|
+
return { ...view(invite), state: "expired" as const };
|
|
182
|
+
}
|
|
183
|
+
return view(invite);
|
|
184
|
+
},
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Sweep up to `batch` invitations in two passes, oldest first. First — the
|
|
189
|
+
* retention sweep — terminal invites whose `createdAt < retentionBefore` are
|
|
190
|
+
* deleted (via `by_state_created` across `accepted`/`revoked`/`expired`). Then,
|
|
191
|
+
* with whatever batch budget remains — the TTL sweep — `pending` invites whose
|
|
192
|
+
* `expiresAt < before` are flipped to `expired` (via `by_state_expires`).
|
|
193
|
+
*
|
|
194
|
+
* Retention runs before TTL deliberately: a `pending` invite flipped to
|
|
195
|
+
* `expired` this pass would otherwise re-qualify for the retention delete in the
|
|
196
|
+
* same pass and be double-counted. Flipping last leaves the freshly-expired rows
|
|
197
|
+
* for the NEXT pass (where `createdAt < retentionBefore` still holds), so each
|
|
198
|
+
* invite is touched once per pass.
|
|
199
|
+
*
|
|
200
|
+
* `before` and `retentionBefore` default to the server clock. If a full batch
|
|
201
|
+
* was touched there may be more, so the sweep self-reschedules through
|
|
202
|
+
* `ctx.scheduler` until a short batch signals the tail is clean. Idempotent —
|
|
203
|
+
* only ever deletes already-terminal, past-retention rows and expires
|
|
204
|
+
* already-stale pending invites. Returns the total touched (deleted + expired)
|
|
205
|
+
* in this pass. The built-in daily cron drives this automatically.
|
|
206
|
+
*/
|
|
207
|
+
export const prune = mutation({
|
|
208
|
+
args: {
|
|
209
|
+
before: v.optional(v.number()),
|
|
210
|
+
retentionBefore: v.optional(v.number()),
|
|
211
|
+
batch: v.number(),
|
|
212
|
+
},
|
|
213
|
+
returns: v.number(),
|
|
214
|
+
handler: async (ctx, args) => {
|
|
215
|
+
const now = Date.now();
|
|
216
|
+
const before = args.before ?? now;
|
|
217
|
+
const retentionBefore = args.retentionBefore ?? now;
|
|
218
|
+
|
|
219
|
+
// Retention sweep: the three terminal states, queried explicitly (no
|
|
220
|
+
// query-in-loop), each consuming whatever batch budget the earlier passes
|
|
221
|
+
// left.
|
|
222
|
+
const accepted = await ctx.db
|
|
223
|
+
.query("invitations")
|
|
224
|
+
.withIndex("by_state_created", (q) =>
|
|
225
|
+
q.eq("state", "accepted").lt("createdAt", retentionBefore),
|
|
226
|
+
)
|
|
227
|
+
.take(args.batch);
|
|
228
|
+
const revoked =
|
|
229
|
+
accepted.length < args.batch
|
|
230
|
+
? await ctx.db
|
|
231
|
+
.query("invitations")
|
|
232
|
+
.withIndex("by_state_created", (q) =>
|
|
233
|
+
q.eq("state", "revoked").lt("createdAt", retentionBefore),
|
|
234
|
+
)
|
|
235
|
+
.take(args.batch - accepted.length)
|
|
236
|
+
: [];
|
|
237
|
+
const expired =
|
|
238
|
+
accepted.length + revoked.length < args.batch
|
|
239
|
+
? await ctx.db
|
|
240
|
+
.query("invitations")
|
|
241
|
+
.withIndex("by_state_created", (q) =>
|
|
242
|
+
q.eq("state", "expired").lt("createdAt", retentionBefore),
|
|
243
|
+
)
|
|
244
|
+
.take(args.batch - accepted.length - revoked.length)
|
|
245
|
+
: [];
|
|
246
|
+
for (const row of [...accepted, ...revoked, ...expired]) {
|
|
247
|
+
await ctx.db.delete("invitations", row._id);
|
|
248
|
+
}
|
|
249
|
+
const removed = accepted.length + revoked.length + expired.length;
|
|
250
|
+
|
|
251
|
+
// TTL sweep: flip stale pending invites with the remaining batch budget.
|
|
252
|
+
const remaining = args.batch - removed;
|
|
253
|
+
const stale =
|
|
254
|
+
remaining > 0
|
|
255
|
+
? await ctx.db
|
|
256
|
+
.query("invitations")
|
|
257
|
+
.withIndex("by_state_expires", (q) =>
|
|
258
|
+
q.eq("state", "pending").lt("expiresAt", before),
|
|
259
|
+
)
|
|
260
|
+
.take(remaining)
|
|
261
|
+
: [];
|
|
262
|
+
for (const row of stale) {
|
|
263
|
+
await ctx.db.patch("invitations", row._id, { state: "expired" });
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const touched = removed + stale.length;
|
|
267
|
+
if (touched === args.batch) {
|
|
268
|
+
await ctx.scheduler.runAfter(0, api.mutations.prune, {
|
|
269
|
+
before,
|
|
270
|
+
retentionBefore,
|
|
271
|
+
batch: args.batch,
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
return touched;
|
|
275
|
+
},
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
/** Project a stored invitation row to its public view (drops internal fields). */
|
|
279
|
+
function view(invite: {
|
|
280
|
+
token: string;
|
|
281
|
+
resourceRef: string;
|
|
282
|
+
role?: unknown;
|
|
283
|
+
inviterRef?: string;
|
|
284
|
+
inviteeRef?: string;
|
|
285
|
+
payload?: unknown;
|
|
286
|
+
state: "pending" | "accepted" | "revoked" | "expired";
|
|
287
|
+
createdAt: number;
|
|
288
|
+
expiresAt: number;
|
|
289
|
+
acceptedAt?: number;
|
|
290
|
+
acceptedBy?: string;
|
|
291
|
+
revokedAt?: number;
|
|
292
|
+
}) {
|
|
293
|
+
return {
|
|
294
|
+
token: invite.token,
|
|
295
|
+
resourceRef: invite.resourceRef,
|
|
296
|
+
role: invite.role,
|
|
297
|
+
inviterRef: invite.inviterRef,
|
|
298
|
+
inviteeRef: invite.inviteeRef,
|
|
299
|
+
payload: invite.payload,
|
|
300
|
+
state: invite.state,
|
|
301
|
+
createdAt: invite.createdAt,
|
|
302
|
+
expiresAt: invite.expiresAt,
|
|
303
|
+
acceptedAt: invite.acceptedAt,
|
|
304
|
+
acceptedBy: invite.acceptedBy,
|
|
305
|
+
revokedAt: invite.revokedAt,
|
|
306
|
+
};
|
|
307
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { v } from "convex/values";
|
|
2
|
+
import { paginationOptsValidator } from "convex/server";
|
|
3
|
+
import { query } from "./_generated/server";
|
|
4
|
+
import { invitationState, invitationView } from "./validators";
|
|
5
|
+
import type { Doc } from "./_generated/dataModel";
|
|
6
|
+
|
|
7
|
+
/** Project a stored invitation row to its public view (drops internal fields). */
|
|
8
|
+
function view(invite: Doc<"invitations">) {
|
|
9
|
+
return {
|
|
10
|
+
token: invite.token,
|
|
11
|
+
resourceRef: invite.resourceRef,
|
|
12
|
+
role: invite.role,
|
|
13
|
+
inviterRef: invite.inviterRef,
|
|
14
|
+
inviteeRef: invite.inviteeRef,
|
|
15
|
+
payload: invite.payload,
|
|
16
|
+
state: invite.state,
|
|
17
|
+
createdAt: invite.createdAt,
|
|
18
|
+
expiresAt: invite.expiresAt,
|
|
19
|
+
acceptedAt: invite.acceptedAt,
|
|
20
|
+
acceptedBy: invite.acceptedBy,
|
|
21
|
+
revokedAt: invite.revokedAt,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The current view of one invitation by its `token`, or `null` if no such
|
|
27
|
+
* invite is held. This is a pure read — it reports the stored `state` as-is and
|
|
28
|
+
* does NOT flip a stale `pending` invite to `expired` (a query cannot write).
|
|
29
|
+
* Read the `expiresAt`/`state` pair, or call the `peek` mutation when you need
|
|
30
|
+
* read-time TTL enforcement.
|
|
31
|
+
*/
|
|
32
|
+
export const getByToken = query({
|
|
33
|
+
args: { token: v.string() },
|
|
34
|
+
returns: v.union(v.null(), invitationView),
|
|
35
|
+
handler: async (ctx, args) => {
|
|
36
|
+
const invite = await ctx.db
|
|
37
|
+
.query("invitations")
|
|
38
|
+
.withIndex("by_token", (q) => q.eq("token", args.token))
|
|
39
|
+
.unique();
|
|
40
|
+
return invite === null ? null : view(invite);
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Page the still-`pending` invitations for one `resourceRef`, oldest first via
|
|
46
|
+
* the `by_resource_state` index. Takes the standard Convex `paginationOpts` and
|
|
47
|
+
* returns the standard paginated envelope (`page`, `isDone`, `continueCursor`)
|
|
48
|
+
* so the host can render an org's open-invite list reactively. Past-TTL invites
|
|
49
|
+
* may still appear `pending` here until a `peek`/`accept`/cron sweep flips them;
|
|
50
|
+
* compare `expiresAt` against the clock to hide stale ones in the host UI.
|
|
51
|
+
*/
|
|
52
|
+
export const listPending = query({
|
|
53
|
+
args: { resourceRef: v.string(), paginationOpts: paginationOptsValidator },
|
|
54
|
+
returns: v.object({
|
|
55
|
+
page: v.array(invitationView),
|
|
56
|
+
isDone: v.boolean(),
|
|
57
|
+
continueCursor: v.string(),
|
|
58
|
+
splitCursor: v.optional(v.union(v.string(), v.null())),
|
|
59
|
+
pageStatus: v.optional(
|
|
60
|
+
v.union(
|
|
61
|
+
v.literal("SplitRecommended"),
|
|
62
|
+
v.literal("SplitRequired"),
|
|
63
|
+
v.null(),
|
|
64
|
+
),
|
|
65
|
+
),
|
|
66
|
+
}),
|
|
67
|
+
handler: async (ctx, args) => {
|
|
68
|
+
const result = await ctx.db
|
|
69
|
+
.query("invitations")
|
|
70
|
+
.withIndex("by_resource_state", (q) =>
|
|
71
|
+
q.eq("resourceRef", args.resourceRef).eq("state", "pending"),
|
|
72
|
+
)
|
|
73
|
+
.order("asc")
|
|
74
|
+
.paginate(args.paginationOpts);
|
|
75
|
+
return { ...result, page: result.page.map(view) };
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Page invitations for one `resourceRef` in a given `state`, oldest first — the
|
|
81
|
+
* general listing `listPending` specializes. Lets the host render accepted /
|
|
82
|
+
* revoked / expired history for an audit surface.
|
|
83
|
+
*/
|
|
84
|
+
export const listByResourceState = query({
|
|
85
|
+
args: {
|
|
86
|
+
resourceRef: v.string(),
|
|
87
|
+
state: invitationState,
|
|
88
|
+
paginationOpts: paginationOptsValidator,
|
|
89
|
+
},
|
|
90
|
+
returns: v.object({
|
|
91
|
+
page: v.array(invitationView),
|
|
92
|
+
isDone: v.boolean(),
|
|
93
|
+
continueCursor: v.string(),
|
|
94
|
+
splitCursor: v.optional(v.union(v.string(), v.null())),
|
|
95
|
+
pageStatus: v.optional(
|
|
96
|
+
v.union(
|
|
97
|
+
v.literal("SplitRecommended"),
|
|
98
|
+
v.literal("SplitRequired"),
|
|
99
|
+
v.null(),
|
|
100
|
+
),
|
|
101
|
+
),
|
|
102
|
+
}),
|
|
103
|
+
handler: async (ctx, args) => {
|
|
104
|
+
const result = await ctx.db
|
|
105
|
+
.query("invitations")
|
|
106
|
+
.withIndex("by_resource_state", (q) =>
|
|
107
|
+
q.eq("resourceRef", args.resourceRef).eq("state", args.state),
|
|
108
|
+
)
|
|
109
|
+
.order("asc")
|
|
110
|
+
.paginate(args.paginationOpts);
|
|
111
|
+
return { ...result, page: result.page.map(view) };
|
|
112
|
+
},
|
|
113
|
+
});
|