@vllnt/convex-consent 0.1.0-canary.600dfc5

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 (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +143 -0
  3. package/dist/client/index.d.ts +156 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +142 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +79 -0
  8. package/dist/client/types.d.ts.map +1 -0
  9. package/dist/client/types.js +3 -0
  10. package/dist/client/types.js.map +1 -0
  11. package/dist/component/_generated/api.d.ts +40 -0
  12. package/dist/component/_generated/api.d.ts.map +1 -0
  13. package/dist/component/_generated/api.js +31 -0
  14. package/dist/component/_generated/api.js.map +1 -0
  15. package/dist/component/_generated/component.d.ts +102 -0
  16. package/dist/component/_generated/component.d.ts.map +1 -0
  17. package/dist/component/_generated/component.js +11 -0
  18. package/dist/component/_generated/component.js.map +1 -0
  19. package/dist/component/_generated/dataModel.d.ts +46 -0
  20. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  21. package/dist/component/_generated/dataModel.js +11 -0
  22. package/dist/component/_generated/dataModel.js.map +1 -0
  23. package/dist/component/_generated/server.d.ts +133 -0
  24. package/dist/component/_generated/server.d.ts.map +1 -0
  25. package/dist/component/_generated/server.js +80 -0
  26. package/dist/component/_generated/server.js.map +1 -0
  27. package/dist/component/convex.config.d.ts +3 -0
  28. package/dist/component/convex.config.d.ts.map +1 -0
  29. package/dist/component/convex.config.js +7 -0
  30. package/dist/component/convex.config.js.map +1 -0
  31. package/dist/component/crons.d.ts +16 -0
  32. package/dist/component/crons.d.ts.map +1 -0
  33. package/dist/component/crons.js +19 -0
  34. package/dist/component/crons.js.map +1 -0
  35. package/dist/component/mutations.d.ts +60 -0
  36. package/dist/component/mutations.d.ts.map +1 -0
  37. package/dist/component/mutations.js +142 -0
  38. package/dist/component/mutations.js.map +1 -0
  39. package/dist/component/queries.d.ts +78 -0
  40. package/dist/component/queries.d.ts.map +1 -0
  41. package/dist/component/queries.js +119 -0
  42. package/dist/component/queries.js.map +1 -0
  43. package/dist/component/schema.d.ts +53 -0
  44. package/dist/component/schema.d.ts.map +1 -0
  45. package/dist/component/schema.js +40 -0
  46. package/dist/component/schema.js.map +1 -0
  47. package/dist/component/validators.d.ts +80 -0
  48. package/dist/component/validators.d.ts.map +1 -0
  49. package/dist/component/validators.js +62 -0
  50. package/dist/component/validators.js.map +1 -0
  51. package/dist/shared.d.ts +30 -0
  52. package/dist/shared.d.ts.map +1 -0
  53. package/dist/shared.js +28 -0
  54. package/dist/shared.js.map +1 -0
  55. package/package.json +99 -0
  56. package/src/client/index.ts +298 -0
  57. package/src/client/types.ts +85 -0
  58. package/src/component/_generated/api.ts +56 -0
  59. package/src/component/_generated/component.ts +127 -0
  60. package/src/component/_generated/dataModel.ts +60 -0
  61. package/src/component/_generated/server.ts +169 -0
  62. package/src/component/convex.config.ts +9 -0
  63. package/src/component/crons.ts +23 -0
  64. package/src/component/mutations.ts +151 -0
  65. package/src/component/queries.ts +142 -0
  66. package/src/component/schema.ts +41 -0
  67. package/src/component/validators.ts +70 -0
  68. package/src/shared.ts +35 -0
  69. package/src/test.ts +15 -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("consent");
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,23 @@
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 — a host that wants a different
7
+ * cadence drives `prune` from its own scheduler instead (the client exposes it).
8
+ * Convex cron definitions are static per deployment, so cadence is a documented
9
+ * module constant rather than a mount-time option; the page size bounds each
10
+ * sweep and `prune` self-reschedules until the stale-event tail is clean.
11
+ */
12
+ export const PRUNE_INTERVAL = { hours: 24 } as const;
13
+
14
+ /** Rows deleted per `prune` pass before the sweep self-reschedules. */
15
+ export const PRUNE_BATCH = 200;
16
+
17
+ const crons = cronJobs();
18
+
19
+ crons.interval("consent:prune", PRUNE_INTERVAL, api.mutations.prune, {
20
+ batch: PRUNE_BATCH,
21
+ });
22
+
23
+ export default crons;
@@ -0,0 +1,151 @@
1
+ import { ConvexError, v } from "convex/values";
2
+ import { api } from "./_generated/api";
3
+ import { mutation } from "./_generated/server";
4
+ import { consentDecision, jsonValue } from "./validators";
5
+
6
+ /**
7
+ * Record a consent decision for a `(subjectRef, purpose)` pair. Appends one
8
+ * immutable row to the `consentEvents` ledger — the GDPR proof — and overwrites
9
+ * the `consentState` projection so the next {@link check}/{@link getState} reads
10
+ * the new decision. `at` is stamped from the server clock (`Date.now()` inside
11
+ * the handler — never caller-supplied), so the ledger order cannot be skewed by a
12
+ * client clock.
13
+ *
14
+ * `subjectRef` and `purpose` are opaque host strings; `version` is the policy
15
+ * version the subject consented to (defaults to the host's `defaultVersion` at
16
+ * the client boundary); `proof` is opaque host evidence stored verbatim. The
17
+ * ledger row is the legal record — it is never mutated, only swept by retention
18
+ * `prune`.
19
+ */
20
+ export const record = mutation({
21
+ args: {
22
+ subjectRef: v.string(),
23
+ purpose: v.string(),
24
+ decision: consentDecision,
25
+ version: v.string(),
26
+ proof: v.optional(jsonValue),
27
+ },
28
+ returns: v.object({ at: v.number() }),
29
+ handler: async (ctx, args) => {
30
+ const at = Date.now();
31
+ await ctx.db.insert("consentEvents", {
32
+ subjectRef: args.subjectRef,
33
+ purpose: args.purpose,
34
+ decision: args.decision,
35
+ version: args.version,
36
+ proof: args.proof,
37
+ at,
38
+ });
39
+
40
+ const existing = await ctx.db
41
+ .query("consentState")
42
+ .withIndex("by_subject_purpose", (q) =>
43
+ q.eq("subjectRef", args.subjectRef).eq("purpose", args.purpose),
44
+ )
45
+ .unique();
46
+ const projection = {
47
+ subjectRef: args.subjectRef,
48
+ purpose: args.purpose,
49
+ decision: args.decision,
50
+ version: args.version,
51
+ at,
52
+ };
53
+ if (existing === null) {
54
+ await ctx.db.insert("consentState", projection);
55
+ } else {
56
+ await ctx.db.patch("consentState", existing._id, projection);
57
+ }
58
+ return { at };
59
+ },
60
+ });
61
+
62
+ /**
63
+ * Withdraw a previously-granted consent — the GDPR Art. 7(3) "as easy to withdraw
64
+ * as to give" path. Appends a `withdrawn` event and projects it, but ONLY when the
65
+ * subject currently holds a `granted` decision for the purpose; withdrawing
66
+ * something never granted is a no-op error rather than a silent ledger entry, so
67
+ * the audit trail stays meaningful.
68
+ *
69
+ * @throws `ConvexError({ code: "NO_CONSENT" })` when no consent was ever recorded
70
+ * for the pair.
71
+ * @throws `ConvexError({ code: "NOT_GRANTED" })` when the current decision is not
72
+ * `granted` (already `denied`/`withdrawn`) — there is nothing to withdraw.
73
+ */
74
+ export const withdraw = mutation({
75
+ args: {
76
+ subjectRef: v.string(),
77
+ purpose: v.string(),
78
+ proof: v.optional(jsonValue),
79
+ },
80
+ returns: v.object({ at: v.number() }),
81
+ handler: async (ctx, args) => {
82
+ const state = await ctx.db
83
+ .query("consentState")
84
+ .withIndex("by_subject_purpose", (q) =>
85
+ q.eq("subjectRef", args.subjectRef).eq("purpose", args.purpose),
86
+ )
87
+ .unique();
88
+ if (state === null) {
89
+ throw new ConvexError({
90
+ code: "NO_CONSENT",
91
+ message: `no consent recorded for "${args.subjectRef}" / "${args.purpose}"`,
92
+ });
93
+ }
94
+ if (state.decision !== "granted") {
95
+ throw new ConvexError({
96
+ code: "NOT_GRANTED",
97
+ message: `consent for "${args.subjectRef}" / "${args.purpose}" is "${state.decision}", not "granted" — nothing to withdraw`,
98
+ });
99
+ }
100
+
101
+ const at = Date.now();
102
+ await ctx.db.insert("consentEvents", {
103
+ subjectRef: args.subjectRef,
104
+ purpose: args.purpose,
105
+ decision: "withdrawn",
106
+ version: state.version,
107
+ proof: args.proof,
108
+ at,
109
+ });
110
+ await ctx.db.patch("consentState", state._id, { decision: "withdrawn", at });
111
+ return { at };
112
+ },
113
+ });
114
+
115
+ /**
116
+ * Delete up to `batch` superseded ledger events whose `at < before`, oldest first
117
+ * via the `by_at` index, and return the count removed in the first pass. `before`
118
+ * defaults to the server clock (`Date.now()`) when omitted, so the built-in cron
119
+ * sweeps exactly the events stale as of the run. If a full batch was removed there
120
+ * may be more, so the sweep self-reschedules through `ctx.scheduler` until a short
121
+ * batch signals the tail is clean.
122
+ *
123
+ * Only the historical `consentEvents` ledger is pruned — the `consentState`
124
+ * projection is the live gate and is never swept, so a host that prunes old proof
125
+ * still gets the correct current decision. Idempotent: only ever removes
126
+ * already-past-retention rows.
127
+ */
128
+ export const prune = mutation({
129
+ args: { before: v.optional(v.number()), batch: v.number() },
130
+ returns: v.number(),
131
+ handler: async (ctx, args) => {
132
+ const before = args.before ?? Date.now();
133
+ const stale = await ctx.db
134
+ .query("consentEvents")
135
+ .withIndex("by_at", (q) => q.lt("at", before))
136
+ .take(args.batch);
137
+
138
+ for (const row of stale) {
139
+ await ctx.db.delete("consentEvents", row._id);
140
+ }
141
+ const removed = stale.length;
142
+
143
+ if (removed === args.batch) {
144
+ await ctx.scheduler.runAfter(0, api.mutations.prune, {
145
+ before,
146
+ batch: args.batch,
147
+ });
148
+ }
149
+ return removed;
150
+ },
151
+ });
@@ -0,0 +1,142 @@
1
+ import { v } from "convex/values";
2
+ import { paginationOptsValidator } from "convex/server";
3
+ import { query } from "./_generated/server";
4
+ import {
5
+ consentCheckView,
6
+ consentEventView,
7
+ consentStateView,
8
+ } from "./validators";
9
+ import type { Doc } from "./_generated/dataModel";
10
+
11
+ /** Project a stored ledger row to its public event view (drops internal fields). */
12
+ function eventView(e: Doc<"consentEvents">) {
13
+ return {
14
+ subjectRef: e.subjectRef,
15
+ purpose: e.purpose,
16
+ decision: e.decision,
17
+ version: e.version,
18
+ proof: e.proof,
19
+ at: e.at,
20
+ };
21
+ }
22
+
23
+ /** Project a stored projection row to its public state view. */
24
+ function stateView(s: Doc<"consentState">) {
25
+ return {
26
+ subjectRef: s.subjectRef,
27
+ purpose: s.purpose,
28
+ decision: s.decision,
29
+ version: s.version,
30
+ at: s.at,
31
+ };
32
+ }
33
+
34
+ /**
35
+ * The runtime gate: may the host process `purpose` for `subjectRef`? Reads the
36
+ * O(1) current-state projection. `granted` is `true` only when the latest
37
+ * decision is `granted` AND — if a `requiredVersion` is supplied — the consented
38
+ * `version` matches it. When the subject granted an older version than required,
39
+ * `stale` is `true` (and `granted` is `false`) so the host re-prompts. With no
40
+ * recorded consent every field is `null`/`false`.
41
+ */
42
+ export const check = query({
43
+ args: {
44
+ subjectRef: v.string(),
45
+ purpose: v.string(),
46
+ requiredVersion: v.optional(v.string()),
47
+ },
48
+ returns: consentCheckView,
49
+ handler: async (ctx, args) => {
50
+ const state = await ctx.db
51
+ .query("consentState")
52
+ .withIndex("by_subject_purpose", (q) =>
53
+ q.eq("subjectRef", args.subjectRef).eq("purpose", args.purpose),
54
+ )
55
+ .unique();
56
+ if (state === null) {
57
+ return {
58
+ granted: false,
59
+ stale: false,
60
+ decision: null,
61
+ version: null,
62
+ at: null,
63
+ };
64
+ }
65
+ const versionMatches =
66
+ args.requiredVersion === undefined ||
67
+ state.version === args.requiredVersion;
68
+ const isGranted = state.decision === "granted";
69
+ return {
70
+ granted: isGranted && versionMatches,
71
+ stale: isGranted && !versionMatches,
72
+ decision: state.decision,
73
+ version: state.version,
74
+ at: state.at,
75
+ };
76
+ },
77
+ });
78
+
79
+ /** The raw current decision for one `(subjectRef, purpose)` pair, or `null`. */
80
+ export const getState = query({
81
+ args: { subjectRef: v.string(), purpose: v.string() },
82
+ returns: v.union(v.null(), consentStateView),
83
+ handler: async (ctx, args) => {
84
+ const state = await ctx.db
85
+ .query("consentState")
86
+ .withIndex("by_subject_purpose", (q) =>
87
+ q.eq("subjectRef", args.subjectRef).eq("purpose", args.purpose),
88
+ )
89
+ .unique();
90
+ return state === null ? null : stateView(state);
91
+ },
92
+ });
93
+
94
+ /** Every current decision held by one subject, across all purposes. */
95
+ export const getStatesForSubject = query({
96
+ args: { subjectRef: v.string() },
97
+ returns: v.array(consentStateView),
98
+ handler: async (ctx, args) => {
99
+ const states = await ctx.db
100
+ .query("consentState")
101
+ .withIndex("by_subject", (q) => q.eq("subjectRef", args.subjectRef))
102
+ .collect();
103
+ return states.map(stateView);
104
+ },
105
+ });
106
+
107
+ /**
108
+ * Page the immutable consent ledger for one `(subjectRef, purpose)` pair,
109
+ * newest-first via the `by_subject_purpose_at` index. Takes the standard Convex
110
+ * `paginationOpts` and returns the standard paginated envelope (`page`, `isDone`,
111
+ * `continueCursor`) — the full proof trail for an audit or a data subject request.
112
+ */
113
+ export const history = query({
114
+ args: {
115
+ subjectRef: v.string(),
116
+ purpose: v.string(),
117
+ paginationOpts: paginationOptsValidator,
118
+ },
119
+ returns: v.object({
120
+ page: v.array(consentEventView),
121
+ isDone: v.boolean(),
122
+ continueCursor: v.string(),
123
+ splitCursor: v.optional(v.union(v.string(), v.null())),
124
+ pageStatus: v.optional(
125
+ v.union(
126
+ v.literal("SplitRecommended"),
127
+ v.literal("SplitRequired"),
128
+ v.null(),
129
+ ),
130
+ ),
131
+ }),
132
+ handler: async (ctx, args) => {
133
+ const result = await ctx.db
134
+ .query("consentEvents")
135
+ .withIndex("by_subject_purpose_at", (q) =>
136
+ q.eq("subjectRef", args.subjectRef).eq("purpose", args.purpose),
137
+ )
138
+ .order("desc")
139
+ .paginate(args.paginationOpts);
140
+ return { ...result, page: result.page.map(eventView) };
141
+ },
142
+ });
@@ -0,0 +1,41 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ import { consentDecision, jsonValue } from "./validators";
4
+
5
+ /**
6
+ * Two sandboxed tables — the consent ledger's own concern.
7
+ *
8
+ * `consentEvents` is the **append-only** legal record (GDPR Art. 7(1) proof): a
9
+ * row is inserted on every grant/deny/withdraw and is NEVER mutated, only ever
10
+ * deleted by the retention prune. `subjectRef` and `purpose` are opaque host
11
+ * strings; `proof` is opaque host evidence (policy hash, IP, UA). The
12
+ * `by_subject_purpose_at` index reads one pair's history newest-first; the
13
+ * `by_at` index drives the oldest-first retention sweep.
14
+ *
15
+ * `consentState` is the derived **current-decision projection** — exactly one
16
+ * row per `(subjectRef, purpose)`, overwritten on each new event. It is the O(1)
17
+ * runtime gate the host queries before processing; `by_subject_purpose` resolves
18
+ * a single pair, `by_subject` lists every purpose for one subject.
19
+ */
20
+ export default defineSchema({
21
+ consentEvents: defineTable({
22
+ subjectRef: v.string(),
23
+ purpose: v.string(),
24
+ decision: consentDecision,
25
+ version: v.string(),
26
+ proof: v.optional(jsonValue),
27
+ at: v.number(),
28
+ })
29
+ .index("by_subject_purpose_at", ["subjectRef", "purpose", "at"])
30
+ .index("by_at", ["at"]),
31
+
32
+ consentState: defineTable({
33
+ subjectRef: v.string(),
34
+ purpose: v.string(),
35
+ decision: consentDecision,
36
+ version: v.string(),
37
+ at: v.number(),
38
+ })
39
+ .index("by_subject_purpose", ["subjectRef", "purpose"])
40
+ .index("by_subject", ["subjectRef"]),
41
+ });
@@ -0,0 +1,70 @@
1
+ import { v } from "convex/values";
2
+
3
+ /**
4
+ * Opaque host-owned proof recorded alongside a consent decision — the evidence
5
+ * that the subject made the choice (a policy hash, an IP, a user agent, a signed
6
+ * token). The component never inspects it; it is last-resort arbitrary data,
7
+ * aliased here rather than left bare in function signatures. The host narrows it
8
+ * at the {@link Consent} client boundary via an optional `proofValidator` parser.
9
+ *
10
+ * This is the single documented `v.any()` escape hatch in the component; the lint
11
+ * rule `convex-rules/no-bare-v-any` is satisfied by routing every arbitrary host
12
+ * proof through this alias instead of a bare `v.any()`.
13
+ */
14
+ export const jsonValue = v.any();
15
+
16
+ /**
17
+ * The three consent decisions a subject can hold for a purpose. `granted` and
18
+ * `denied` are explicit answers to the consent prompt; `withdrawn` revokes a
19
+ * prior grant. Every decision is appended to the immutable ledger — the GDPR
20
+ * proof — and projected onto the current-state row.
21
+ */
22
+ export const consentDecision = v.union(
23
+ v.literal("granted"),
24
+ v.literal("denied"),
25
+ v.literal("withdrawn"),
26
+ );
27
+
28
+ /**
29
+ * One immutable row in the consent ledger. `subjectRef` and `purpose` are opaque
30
+ * host strings; `decision` is the recorded answer; `version` is the policy
31
+ * version the subject consented to; `proof` is the opaque host evidence; `at` is
32
+ * the server timestamp. The ledger is append-only — a row is never mutated.
33
+ */
34
+ export const consentEventView = v.object({
35
+ subjectRef: v.string(),
36
+ purpose: v.string(),
37
+ decision: consentDecision,
38
+ version: v.string(),
39
+ proof: v.optional(jsonValue),
40
+ at: v.number(),
41
+ });
42
+
43
+ /**
44
+ * The current decision for one `(subjectRef, purpose)` pair — the O(1) runtime
45
+ * gate, projected from the latest ledger event. `null` is returned by
46
+ * {@link check}/{@link getState} when no event was ever recorded.
47
+ */
48
+ export const consentStateView = v.object({
49
+ subjectRef: v.string(),
50
+ purpose: v.string(),
51
+ decision: consentDecision,
52
+ version: v.string(),
53
+ at: v.number(),
54
+ });
55
+
56
+ /**
57
+ * The answer to "may I process `<purpose>` for `<subject>`?". `granted` is the
58
+ * gate: `true` only when the latest decision is `granted` AND its `version`
59
+ * matches the host-supplied `requiredVersion` (or no version was required).
60
+ * `stale` is `true` when the subject granted an older policy version than the one
61
+ * now required — the host re-prompts. `decision`/`version`/`at` mirror the
62
+ * current state (all `null` when no event was ever recorded).
63
+ */
64
+ export const consentCheckView = v.object({
65
+ granted: v.boolean(),
66
+ stale: v.boolean(),
67
+ decision: v.union(consentDecision, v.null()),
68
+ version: v.union(v.string(), v.null()),
69
+ at: v.union(v.number(), v.null()),
70
+ });