@vllnt/convex-invitations 0.1.0 → 0.1.1-canary.235fcf7

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 (44) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/README.md +156 -50
  3. package/dist/client/index.d.ts +5 -2
  4. package/dist/client/index.d.ts.map +1 -1
  5. package/dist/client/index.js +5 -2
  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/crons.js +1 -1
  10. package/dist/component/crons.js.map +1 -1
  11. package/dist/component/guards.d.ts +7 -0
  12. package/dist/component/guards.d.ts.map +1 -0
  13. package/dist/component/guards.js +23 -0
  14. package/dist/component/guards.js.map +1 -0
  15. package/dist/component/legacyToken.d.ts +2 -2
  16. package/dist/component/legacyToken.d.ts.map +1 -1
  17. package/dist/component/mutations.d.ts +3 -3
  18. package/dist/component/mutations.d.ts.map +1 -1
  19. package/dist/component/mutations.js +29 -10
  20. package/dist/component/mutations.js.map +1 -1
  21. package/dist/component/queries.d.ts +1 -1
  22. package/dist/component/queries.d.ts.map +1 -1
  23. package/dist/component/queries.js +9 -6
  24. package/dist/component/queries.js.map +1 -1
  25. package/dist/component/schema.js +1 -1
  26. package/dist/component/schema.js.map +1 -1
  27. package/dist/component/token.d.ts +1 -0
  28. package/dist/component/token.d.ts.map +1 -1
  29. package/dist/component/token.js +4 -1
  30. package/dist/component/token.js.map +1 -1
  31. package/docs/API.md +206 -0
  32. package/llms.txt +36 -0
  33. package/package.json +38 -19
  34. package/src/client/index.ts +5 -2
  35. package/src/client/types.ts +7 -4
  36. package/src/component/crons.ts +1 -1
  37. package/src/component/guards.ts +26 -0
  38. package/src/component/legacyToken.ts +2 -2
  39. package/src/component/mutations.ts +25 -10
  40. package/src/component/queries.ts +9 -7
  41. package/src/component/schema.ts +1 -1
  42. package/src/component/token.ts +5 -1
  43. package/src/test.ts +2 -1
  44. package/src/component/migration.test.ts +0 -110
@@ -6,8 +6,9 @@ export type InvitationState = "pending" | "accepted" | "revoked" | "expired";
6
6
  /**
7
7
  * Validates and narrows an opaque stored value to a host type `T` at the client
8
8
  * boundary. Receives the raw value the component returned (`unknown`) and MUST
9
- * return a typed `T` or throw. A `convex/values` validator's `.parse` (or a Zod
10
- * `.parse`) fits directly; omit it to keep the value unvalidated.
9
+ * return a typed `T` or throw. A Zod schema's `.parse` fits directly; Convex
10
+ * `v.*` validators have no `.parse`, so wrap a check in a function instead. Omit
11
+ * it to keep the value unvalidated.
11
12
  *
12
13
  * @typeParam T - The host's stored type (invitation `role` or `payload`).
13
14
  */
@@ -92,12 +93,14 @@ export interface InvitationsOptions<TRole, TPayload> {
92
93
  /**
93
94
  * Validates/narrows a stored `role` to `TRole` at the boundary — applied to the
94
95
  * `role` passed into `issue` (before storage) and the `role` returned by
95
- * `getByToken`/`accept`. Throws on a mismatch. Omit to leave roles unvalidated.
96
+ * `accept`/`peek`/`getByToken`/`listPending`/`listByResourceState`. Throws on a
97
+ * mismatch. Omit to leave roles unvalidated.
96
98
  */
97
99
  roleValidator?: Parser<TRole>;
98
100
  /**
99
101
  * Validates/narrows a stored `payload` to `TPayload` at the boundary — applied
100
- * to the `payload` passed into `issue` and returned by `getByToken`/`accept`.
102
+ * to the `payload` passed into `issue` and returned by
103
+ * `accept`/`peek`/`getByToken`/`listPending`/`listByResourceState`.
101
104
  * Throws on a mismatch. Omit to leave payloads unvalidated.
102
105
  */
103
106
  payloadValidator?: Parser<TPayload>;
@@ -1,5 +1,5 @@
1
1
  import { cronJobs } from "convex/server";
2
- import { api } from "./_generated/api";
2
+ import { api } from "./_generated/api.js";
3
3
 
4
4
  /**
5
5
  * Default sweep cadence and page size for the built-in prune cron. The cron is
@@ -0,0 +1,26 @@
1
+ import { ConvexError } from "convex/values";
2
+
3
+ function invalidArgument(message: string): ConvexError<{ code: string; message: string }> {
4
+ return new ConvexError({ code: "INVALID_ARGUMENT", message });
5
+ }
6
+
7
+ /** Reject an empty host-supplied reference (`resourceRef`, `acceptedBy`, ...). */
8
+ export function requireNonEmpty(name: string, value: string): void {
9
+ if (value.length === 0) {
10
+ throw invalidArgument(`${name} must not be empty`);
11
+ }
12
+ }
13
+
14
+ /** Reject NaN and +/-Infinity where a concrete timestamp is required. */
15
+ export function requireFiniteTime(name: string, value: number): void {
16
+ if (!Number.isFinite(value)) {
17
+ throw invalidArgument(`${name} must be a finite number`);
18
+ }
19
+ }
20
+
21
+ /** Reject NaN; an infinite cutoff is a deliberate "everything" bound. */
22
+ export function requireNotNaN(name: string, value: number): void {
23
+ if (Number.isNaN(value)) {
24
+ throw invalidArgument(`${name} must not be NaN`);
25
+ }
26
+ }
@@ -1,5 +1,5 @@
1
- import type { Doc } from "./_generated/dataModel";
2
- import type { MutationCtx, QueryCtx } from "./_generated/server";
1
+ import type { Doc } from "./_generated/dataModel.js";
2
+ import type { MutationCtx, QueryCtx } from "./_generated/server.js";
3
3
 
4
4
  export async function migrateLegacyToken(
5
5
  db: MutationCtx["db"],
@@ -1,10 +1,11 @@
1
1
  import { ConvexError, v } from "convex/values";
2
- import { api } from "./_generated/api";
3
- import { mutation } from "./_generated/server";
4
- import { DEFAULT_RETENTION_MS } from "../shared";
5
- import { migrateLegacyToken, withLegacyTokenFallback } from "./legacyToken";
6
- import { tokenDigest, validateToken } from "./token";
7
- import { invitationView, jsonValue } from "./validators";
2
+ import { api } from "./_generated/api.js";
3
+ import { mutation } from "./_generated/server.js";
4
+ import { DEFAULT_RETENTION_MS } from "../shared.js";
5
+ import { migrateLegacyToken, withLegacyTokenFallback } from "./legacyToken.js";
6
+ import { requireFiniteTime, requireNonEmpty, requireNotNaN } from "./guards.js";
7
+ import { tokenDigest, validateToken } from "./token.js";
8
+ import { invitationView, jsonValue } from "./validators.js";
8
9
 
9
10
  const DEFAULT_MIGRATION_BATCH = 50;
10
11
  const MAX_MIGRATION_BATCH = 100;
@@ -36,6 +37,17 @@ export const issue = mutation({
36
37
  returns: v.object({ token: v.string(), expiresAt: v.number() }),
37
38
  handler: async (ctx, args) => {
38
39
  validateToken(args.token);
40
+ requireNonEmpty("resourceRef", args.resourceRef);
41
+ if (args.inviterRef !== undefined) requireNonEmpty("inviterRef", args.inviterRef);
42
+ if (args.inviteeRef !== undefined) requireNonEmpty("inviteeRef", args.inviteeRef);
43
+ requireFiniteTime("expiresAt", args.expiresAt);
44
+ const createdAt = Date.now();
45
+ if (args.expiresAt <= createdAt) {
46
+ throw new ConvexError({
47
+ code: "INVALID_ARGUMENT",
48
+ message: "expiresAt must be in the future",
49
+ });
50
+ }
39
51
  const tokenHash = await tokenDigest(args.token);
40
52
  const existingHash = await ctx.db
41
53
  .query("invitations")
@@ -60,7 +72,7 @@ export const issue = mutation({
60
72
  inviteeRef: args.inviteeRef,
61
73
  payload: args.payload,
62
74
  state: "pending",
63
- createdAt: Date.now(),
75
+ createdAt,
64
76
  expiresAt: args.expiresAt,
65
77
  });
66
78
  return { token: args.token, expiresAt: args.expiresAt };
@@ -140,6 +152,7 @@ export const accept = mutation({
140
152
  }),
141
153
  handler: async (ctx, args) => {
142
154
  validateToken(args.token);
155
+ requireNonEmpty("acceptedBy", args.acceptedBy);
143
156
  const tokenHash = await tokenDigest(args.token);
144
157
  const hashed = await ctx.db
145
158
  .query("invitations")
@@ -224,9 +237,9 @@ export const revoke = mutation({
224
237
  /**
225
238
  * The current view of one invitation by its `token`, or `null` if no such
226
239
  * invite is held. Lives in `mutations.ts` (not `queries.ts`) because it flips a
227
- * `pending` invite found past its TTL to `expired` before returning — the same
228
- * read-time TTL enforcement `accept` does, so a status check never reports a
229
- * stale invite as still open.
240
+ * `pending` invite found past its TTL to `expired` before returning — unlike
241
+ * `accept`, which rejects a stale invite but cannot persist the flip — so a
242
+ * status check never reports a stale invite as still open.
230
243
  */
231
244
  export const peek = mutation({
232
245
  args: { token: v.string() },
@@ -285,6 +298,8 @@ export const prune = mutation({
285
298
  message: "batch must be an integer between 1 and 500",
286
299
  });
287
300
  }
301
+ if (args.before !== undefined) requireNotNaN("before", args.before);
302
+ if (args.retentionBefore !== undefined) requireNotNaN("retentionBefore", args.retentionBefore);
288
303
  const now = Date.now();
289
304
  const before = args.before ?? now;
290
305
  const retentionBefore = args.retentionBefore ?? now - DEFAULT_RETENTION_MS;
@@ -1,10 +1,10 @@
1
1
  import { v } from "convex/values";
2
2
  import { paginationOptsValidator } from "convex/server";
3
- import { query } from "./_generated/server";
4
- import { withLegacyTokenFallback } from "./legacyToken";
5
- import { tokenDigest, validateToken } from "./token";
6
- import { invitationMetadataView, invitationState, invitationView } from "./validators";
7
- import type { Doc } from "./_generated/dataModel";
3
+ import { query } from "./_generated/server.js";
4
+ import { withLegacyTokenFallback } from "./legacyToken.js";
5
+ import { isValidToken, tokenDigest } from "./token.js";
6
+ import { invitationMetadataView, invitationState, invitationView } from "./validators.js";
7
+ import type { Doc } from "./_generated/dataModel.js";
8
8
 
9
9
  /** Project a stored invitation row to its public view (drops internal fields). */
10
10
  function metadataView(invite: Doc<"invitations">) {
@@ -51,7 +51,9 @@ export const getByToken = query({
51
51
  args: { token: v.string() },
52
52
  returns: v.union(v.null(), invitationView),
53
53
  handler: async (ctx, args) => {
54
- validateToken(args.token);
54
+ // No invitation can hold a token of invalid length, so a reactive read with a
55
+ // placeholder value reports "not found" instead of throwing.
56
+ if (!isValidToken(args.token)) return null;
55
57
  const tokenHash = await tokenDigest(args.token);
56
58
  const hashed = await ctx.db
57
59
  .query("invitations")
@@ -67,7 +69,7 @@ export const getByToken = query({
67
69
  * the `by_resource_state` index. Takes the standard Convex `paginationOpts` and
68
70
  * returns the standard paginated envelope (`page`, `isDone`, `continueCursor`)
69
71
  * so the host can render an org's open-invite list reactively. Past-TTL invites
70
- * may still appear `pending` here until a `peek`/`accept`/cron sweep flips them;
72
+ * may still appear `pending` here until a `peek`/cron sweep flips them;
71
73
  * compare `expiresAt` against the clock to hide stale ones in the host UI.
72
74
  */
73
75
  export const listPending = query({
@@ -1,6 +1,6 @@
1
1
  import { defineSchema, defineTable } from "convex/server";
2
2
  import { v } from "convex/values";
3
- import { invitationState, jsonValue } from "./validators";
3
+ import { invitationState, jsonValue } from "./validators.js";
4
4
 
5
5
  /**
6
6
  * Sandboxed table — the invitation's own concern. A `tokenHash` is the
@@ -3,8 +3,12 @@ import { ConvexError } from "convex/values";
3
3
  const encoder = new TextEncoder();
4
4
  const MAX_TOKEN_LENGTH = 512;
5
5
 
6
+ export function isValidToken(token: string): boolean {
7
+ return token.length > 0 && token.length <= MAX_TOKEN_LENGTH;
8
+ }
9
+
6
10
  export function validateToken(token: string): void {
7
- if (token.length === 0 || token.length > MAX_TOKEN_LENGTH) {
11
+ if (!isValidToken(token)) {
8
12
  throw new ConvexError({
9
13
  code: "INVALID_TOKEN",
10
14
  message: `token must be between 1 and ${MAX_TOKEN_LENGTH} characters`,
package/src/test.ts CHANGED
@@ -1,5 +1,6 @@
1
+ /// <reference types="vite/client" />
1
2
  import type { TestConvex } from "convex-test";
2
- import schema from "./component/schema";
3
+ import schema from "./component/schema.js";
3
4
 
4
5
  const modules = import.meta.glob("./component/**/*.ts");
5
6
 
@@ -1,110 +0,0 @@
1
- /// <reference types="vite/client" />
2
- import { convexTest } from "convex-test";
3
- import { expect, test, vi } from "vitest";
4
- import { api } from "./_generated/api";
5
- import schema from "./schema";
6
- import { tokenDigest } from "./token";
7
-
8
- const modules = import.meta.glob("./**/*.ts");
9
-
10
- function setup() {
11
- return convexTest(schema, modules);
12
- }
13
-
14
- async function seedLegacy(t: ReturnType<typeof setup>, token: string) {
15
- return t.run((ctx) =>
16
- ctx.db.insert("invitations", {
17
- token,
18
- resourceRef: "resource",
19
- state: "pending",
20
- createdAt: Date.now(),
21
- expiresAt: Date.now() + 60_000,
22
- }),
23
- );
24
- }
25
-
26
- test("new invitations persist only a token digest", async () => {
27
- const t = setup();
28
- const token = "new-secret";
29
- await t.mutation(api.mutations.issue, {
30
- token,
31
- resourceRef: "resource",
32
- expiresAt: Date.now() + 60_000,
33
- });
34
- const digest = await tokenDigest(token);
35
- const stored = await t.run((ctx) =>
36
- ctx.db
37
- .query("invitations")
38
- .withIndex("by_token_hash", (q) => q.eq("tokenHash", digest))
39
- .unique(),
40
- );
41
- expect(stored?.tokenHash).toBe(digest);
42
- expect(stored?.token).toBeUndefined();
43
- });
44
-
45
- test("accepting a legacy invitation removes the raw bearer token", async () => {
46
- const t = setup();
47
- const token = "legacy-accept";
48
- const id = await seedLegacy(t, token);
49
- await t.mutation(api.mutations.accept, { token, acceptedBy: "subject" });
50
- const stored = await t.run((ctx) => ctx.db.get("invitations", id));
51
- expect(stored?.token).toBeUndefined();
52
- expect(stored?.tokenHash).toBe(await tokenDigest(token));
53
- expect(stored?.state).toBe("accepted");
54
- });
55
-
56
- test("legacy lookup and duplicate detection work before background migration", async () => {
57
- const t = setup();
58
- const token = "legacy-lookup";
59
- await seedLegacy(t, token);
60
- expect((await t.query(api.queries.getByToken, { token }))?.resourceRef).toBe("resource");
61
- await expect(
62
- t.mutation(api.mutations.issue, {
63
- token,
64
- resourceRef: "other",
65
- expiresAt: Date.now() + 60_000,
66
- }),
67
- ).rejects.toThrow(/DUPLICATE_TOKEN|already exists/);
68
- });
69
-
70
- test("bounded migration hashes legacy tokens and self-drains", async () => {
71
- vi.useFakeTimers();
72
- try {
73
- const t = setup();
74
- const first = await seedLegacy(t, "");
75
- const second = await seedLegacy(t, "legacy-two");
76
- expect(await t.mutation(api.mutations.migrateLegacyTokens, { batch: 1 })).toBe(1);
77
- await t.finishAllScheduledFunctions(vi.runAllTimers);
78
- for (const id of [first, second]) {
79
- const stored = await t.run((ctx) => ctx.db.get("invitations", id));
80
- expect(stored?.token).toBeUndefined();
81
- expect(stored?.tokenHash).toMatch(/^[a-f0-9]{64}$/);
82
- }
83
- } finally {
84
- vi.useRealTimers();
85
- }
86
- });
87
-
88
- test.each(["", "x".repeat(513)])("rejects invalid bearer token length", async (token) => {
89
- const t = setup();
90
- await expect(
91
- t.mutation(api.mutations.issue, {
92
- token,
93
- resourceRef: "resource",
94
- expiresAt: Date.now() + 60_000,
95
- }),
96
- ).rejects.toThrow(/INVALID_TOKEN|between 1 and 512/);
97
- await expect(t.query(api.queries.getByToken, { token })).rejects.toThrow(
98
- /INVALID_TOKEN|between 1 and 512/,
99
- );
100
- });
101
-
102
- test.each([Number.NaN, 0, -1, 1.5, 101])(
103
- "legacy migration rejects invalid batch %s",
104
- async (batch) => {
105
- const t = setup();
106
- await expect(
107
- t.mutation(api.mutations.migrateLegacyTokens, { batch }),
108
- ).rejects.toThrow(/INVALID_BATCH|integer between/);
109
- },
110
- );