@vllnt/convex-tokens 0.1.0-canary.4f0e428

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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +127 -0
  3. package/dist/client/index.d.ts +116 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +92 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +59 -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 +71 -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 +121 -0
  24. package/dist/component/_generated/server.d.ts.map +1 -0
  25. package/dist/component/_generated/server.js +78 -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 +10 -0
  32. package/dist/component/crons.d.ts.map +1 -0
  33. package/dist/component/crons.js +13 -0
  34. package/dist/component/crons.js.map +1 -0
  35. package/dist/component/mutations.d.ts +49 -0
  36. package/dist/component/mutations.d.ts.map +1 -0
  37. package/dist/component/mutations.js +141 -0
  38. package/dist/component/mutations.js.map +1 -0
  39. package/dist/component/queries.d.ts +51 -0
  40. package/dist/component/queries.d.ts.map +1 -0
  41. package/dist/component/queries.js +84 -0
  42. package/dist/component/queries.js.map +1 -0
  43. package/dist/component/schema.d.ts +30 -0
  44. package/dist/component/schema.d.ts.map +1 -0
  45. package/dist/component/schema.js +23 -0
  46. package/dist/component/schema.js.map +1 -0
  47. package/dist/component/validators.d.ts +45 -0
  48. package/dist/component/validators.d.ts.map +1 -0
  49. package/dist/component/validators.js +24 -0
  50. package/dist/component/validators.js.map +1 -0
  51. package/dist/react/index.d.ts +35 -0
  52. package/dist/react/index.d.ts.map +1 -0
  53. package/dist/react/index.js +30 -0
  54. package/dist/react/index.js.map +1 -0
  55. package/dist/shared.d.ts +60 -0
  56. package/dist/shared.d.ts.map +1 -0
  57. package/dist/shared.js +69 -0
  58. package/dist/shared.js.map +1 -0
  59. package/package.json +112 -0
  60. package/src/client/index.ts +220 -0
  61. package/src/client/types.ts +60 -0
  62. package/src/component/_generated/api.ts +56 -0
  63. package/src/component/_generated/component.ts +93 -0
  64. package/src/component/_generated/dataModel.ts +60 -0
  65. package/src/component/_generated/server.ts +156 -0
  66. package/src/component/convex.config.ts +9 -0
  67. package/src/component/crons.ts +19 -0
  68. package/src/component/mutations.ts +158 -0
  69. package/src/component/queries.ts +90 -0
  70. package/src/component/schema.ts +23 -0
  71. package/src/component/validators.ts +28 -0
  72. package/src/react/index.test.tsx +86 -0
  73. package/src/react/index.tsx +41 -0
  74. package/src/shared.ts +98 -0
  75. package/src/test.ts +12 -0
  76. package/src/unit.test.ts +48 -0
@@ -0,0 +1,158 @@
1
+ import { v } from "convex/values";
2
+ import { ConvexError } from "convex/values";
3
+ import { internalMutation, mutation } from "./_generated/server";
4
+ import { internal } from "./_generated/api";
5
+ import {
6
+ clampTtl,
7
+ DEFAULT_REVOKED_RETENTION_MS,
8
+ MIN_TTL_MS,
9
+ PRUNE_BATCH,
10
+ } from "../shared";
11
+
12
+ /**
13
+ * Minimum length of a valid hex digest (SHA-256 = 64 hex chars).
14
+ *
15
+ * The component only stores hashes — a `tokenHash` shorter than this or
16
+ * containing non-hex characters is not a plausible digest and is rejected. This
17
+ * guards against a misconfigured or adversarial host calling the component
18
+ * mutation directly and persisting a raw secret or garbage string.
19
+ */
20
+ const MIN_HASH_LENGTH = 64;
21
+
22
+ /** Pattern that a plausible hex digest must satisfy (lowercase hex only). */
23
+ const HASH_PATTERN = /^[0-9a-f]+$/;
24
+
25
+ /**
26
+ * Mint a token. The component computes `expiresAt` itself from a requested
27
+ * `ttlMs` — it never trusts a client-supplied timestamp. `ttlMs` is clamped into
28
+ * `[MIN_TTL_MS, maxTtlMs]`; a non-finite `ttlMs` (NaN / Infinity) falls back to
29
+ * `defaultTtlMs`. This guarantees a minted token always outlives a `Date.now()`
30
+ * validate (the floor is `MIN_TTL_MS`).
31
+ */
32
+ export const mint = mutation({
33
+ args: {
34
+ tokenHash: v.string(),
35
+ scope: v.string(),
36
+ resourceRef: v.optional(v.string()),
37
+ ttlMs: v.number(),
38
+ defaultTtlMs: v.number(),
39
+ maxTtlMs: v.number(),
40
+ },
41
+ returns: v.id("tokens"),
42
+ handler: async (ctx, args) => {
43
+ const isPlausibleHash =
44
+ args.tokenHash.length >= MIN_HASH_LENGTH &&
45
+ HASH_PATTERN.test(args.tokenHash);
46
+ if (!isPlausibleHash) {
47
+ throw new ConvexError({
48
+ code: "INVALID_TOKEN_HASH",
49
+ message:
50
+ "tokenHash must be a lowercase hex digest of at least 64 characters (SHA-256 minimum). " +
51
+ "Use client.hashToken() to produce a valid hash.",
52
+ });
53
+ }
54
+ const ttl = clampTtl(args.ttlMs, MIN_TTL_MS, args.maxTtlMs, args.defaultTtlMs);
55
+ const now = Date.now();
56
+ return await ctx.db.insert("tokens", {
57
+ tokenHash: args.tokenHash,
58
+ scope: args.scope,
59
+ resourceRef: args.resourceRef,
60
+ revoked: false,
61
+ expiresAt: now + ttl,
62
+ createdAt: now,
63
+ });
64
+ },
65
+ });
66
+
67
+ /**
68
+ * Revoke the token with `tokenHash` in `scope`.
69
+ *
70
+ * Returns `true` **only if this call transitioned the token from active to
71
+ * revoked** (i.e. it existed in the given scope and was not already revoked).
72
+ * Returns `false` for an unknown token, a wrong-scope token, or a token that
73
+ * is already in the revoked state — the caller can distinguish "nothing to
74
+ * revoke" from "successfully revoked".
75
+ *
76
+ * @remarks This is the "true = transition" contract, not "true = now revoked".
77
+ * Calling revoke twice on the same token returns `true` the first time and
78
+ * `false` the second time. Use `getMetadata` to check the current state
79
+ * without side effects.
80
+ */
81
+ export const revoke = mutation({
82
+ args: { tokenHash: v.string(), scope: v.string() },
83
+ returns: v.boolean(),
84
+ handler: async (ctx, args) => {
85
+ const row = await ctx.db
86
+ .query("tokens")
87
+ .withIndex("by_hash", (q) => q.eq("tokenHash", args.tokenHash))
88
+ .unique();
89
+ if (row === null || row.scope !== args.scope || row.revoked) {
90
+ return false;
91
+ }
92
+ await ctx.db.patch(row._id, { revoked: true });
93
+ return true;
94
+ },
95
+ });
96
+
97
+ /**
98
+ * Delete up to `PRUNE_BATCH` tokens that expired before `before` (bounded read
99
+ * via `by_expires`). Returns the count deleted in this batch. Idempotent and
100
+ * bounded — safe to schedule; callers loop until it returns < `PRUNE_BATCH`.
101
+ */
102
+ export const prune = mutation({
103
+ args: { before: v.number() },
104
+ returns: v.number(),
105
+ handler: async (ctx, args) => {
106
+ const expired = await ctx.db
107
+ .query("tokens")
108
+ .withIndex("by_expires", (q) => q.lt("expiresAt", args.before))
109
+ .take(PRUNE_BATCH);
110
+ for (const row of expired) {
111
+ await ctx.db.delete(row._id);
112
+ }
113
+ return expired.length;
114
+ },
115
+ });
116
+
117
+ /**
118
+ * Cron-driven sweep. Deletes, in bounded batches, (1) expired tokens and (2)
119
+ * revoked tokens older than `revokedRetentionMs` (so an early-revoked token does
120
+ * not linger for its full TTL). Self-reschedules while a batch fills, so an
121
+ * unbounded backlog is drained without exceeding read limits.
122
+ */
123
+ export const pruneExpired = internalMutation({
124
+ args: {},
125
+ returns: v.null(),
126
+ handler: async (ctx) => {
127
+ const now = Date.now();
128
+
129
+ const expired = await ctx.db
130
+ .query("tokens")
131
+ .withIndex("by_expires", (q) => q.lt("expiresAt", now))
132
+ .take(PRUNE_BATCH);
133
+ for (const row of expired) {
134
+ await ctx.db.delete(row._id);
135
+ }
136
+
137
+ let revokedDeleted = 0;
138
+ const remaining = PRUNE_BATCH - expired.length;
139
+ if (remaining > 0) {
140
+ const revokedCutoff = now - DEFAULT_REVOKED_RETENTION_MS;
141
+ const staleRevoked = await ctx.db
142
+ .query("tokens")
143
+ .withIndex("by_revoked_created", (q) =>
144
+ q.eq("revoked", true).lt("createdAt", revokedCutoff),
145
+ )
146
+ .take(remaining);
147
+ for (const row of staleRevoked) {
148
+ await ctx.db.delete(row._id);
149
+ }
150
+ revokedDeleted = staleRevoked.length;
151
+ }
152
+
153
+ if (expired.length + revokedDeleted === PRUNE_BATCH) {
154
+ await ctx.scheduler.runAfter(0, internal.mutations.pruneExpired, {});
155
+ }
156
+ return null;
157
+ },
158
+ });
@@ -0,0 +1,90 @@
1
+ import { v } from "convex/values";
2
+ import { query } from "./_generated/server";
3
+ import { tokenMetadata, validateResult } from "./validators";
4
+ import { LIST_LIMIT_MAX } from "../shared.js";
5
+
6
+ /**
7
+ * Validate a token by its hash. Reads the current time from `Date.now()` INSIDE
8
+ * the handler — there is no client-supplied `now`, so an expired token cannot be
9
+ * revived by passing a stale timestamp. Returns `{ valid: false }` for unknown,
10
+ * wrong-scope, revoked, or expired tokens.
11
+ */
12
+ export const validate = query({
13
+ args: { tokenHash: v.string(), scope: v.string() },
14
+ returns: validateResult,
15
+ handler: async (ctx, args) => {
16
+ const now = Date.now();
17
+ const row = await ctx.db
18
+ .query("tokens")
19
+ .withIndex("by_hash", (q) => q.eq("tokenHash", args.tokenHash))
20
+ .unique();
21
+ if (
22
+ row === null ||
23
+ row.scope !== args.scope ||
24
+ row.revoked ||
25
+ row.expiresAt <= now
26
+ ) {
27
+ return { valid: false };
28
+ }
29
+ return { valid: true, resourceRef: row.resourceRef };
30
+ },
31
+ });
32
+
33
+ /**
34
+ * List token METADATA for a management surface, projecting only non-secret
35
+ * lifecycle fields — NEVER `tokenHash`. Filters by `scope` and optional
36
+ * `resourceRef` via the `by_scope_resource` index (a bounded lookup, not a
37
+ * table scan). Returns up to `limit` (default 100, ceiling {@link LIST_LIMIT_MAX})
38
+ * rows. A `limit` above the ceiling is silently clamped; `limit: 0` returns an
39
+ * empty array.
40
+ */
41
+ export const list = query({
42
+ args: {
43
+ scope: v.string(),
44
+ resourceRef: v.optional(v.string()),
45
+ limit: v.optional(v.number()),
46
+ },
47
+ returns: v.array(tokenMetadata),
48
+ handler: async (ctx, args) => {
49
+ const limit = Math.min(args.limit ?? 100, LIST_LIMIT_MAX);
50
+ const rows = await ctx.db
51
+ .query("tokens")
52
+ .withIndex("by_scope_resource", (q) =>
53
+ args.resourceRef === undefined
54
+ ? q.eq("scope", args.scope)
55
+ : q.eq("scope", args.scope).eq("resourceRef", args.resourceRef),
56
+ )
57
+ .take(limit);
58
+ return rows.map((row) => ({
59
+ id: row._id,
60
+ scope: row.scope,
61
+ resourceRef: row.resourceRef,
62
+ revoked: row.revoked,
63
+ expiresAt: row.expiresAt,
64
+ createdAt: row.createdAt,
65
+ }));
66
+ },
67
+ });
68
+
69
+ /**
70
+ * Fetch the safe METADATA of a single token by its component id — no
71
+ * `tokenHash`. Returns `null` if no such row.
72
+ */
73
+ export const getMetadata = query({
74
+ args: { id: v.id("tokens") },
75
+ returns: v.union(tokenMetadata, v.null()),
76
+ handler: async (ctx, args) => {
77
+ const row = await ctx.db.get(args.id);
78
+ if (row === null) {
79
+ return null;
80
+ }
81
+ return {
82
+ id: row._id,
83
+ scope: row.scope,
84
+ resourceRef: row.resourceRef,
85
+ revoked: row.revoked,
86
+ expiresAt: row.expiresAt,
87
+ createdAt: row.createdAt,
88
+ };
89
+ },
90
+ });
@@ -0,0 +1,23 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+
4
+ /**
5
+ * Sandboxed tables — the token registry's own concern. Only the SHA-256 (or
6
+ * SHA-512) hash of a token is stored (`tokenHash`); the raw secret is never
7
+ * persisted. `scope` namespaces tokens and `resourceRef` is an opaque host-owned
8
+ * reference (never assume its shape).
9
+ */
10
+ export default defineSchema({
11
+ tokens: defineTable({
12
+ tokenHash: v.string(),
13
+ scope: v.string(),
14
+ resourceRef: v.optional(v.string()),
15
+ revoked: v.boolean(),
16
+ expiresAt: v.number(),
17
+ createdAt: v.number(),
18
+ })
19
+ .index("by_hash", ["tokenHash"])
20
+ .index("by_expires", ["expiresAt"])
21
+ .index("by_scope_resource", ["scope", "resourceRef"])
22
+ .index("by_revoked_created", ["revoked", "createdAt"]),
23
+ });
@@ -0,0 +1,28 @@
1
+ import { v } from "convex/values";
2
+
3
+ /**
4
+ * Result of validating a token hash.
5
+ *
6
+ * Discriminated union on `valid`:
7
+ * - `{ valid: true, resourceRef? }` — the token is live and carries an optional
8
+ * opaque host-owned reference.
9
+ * - `{ valid: false }` — the token is unknown, wrong-scope, revoked, or expired.
10
+ * The failed branch structurally cannot carry `resourceRef`.
11
+ */
12
+ export const validateResult = v.union(
13
+ v.object({ valid: v.literal(true), resourceRef: v.optional(v.string()) }),
14
+ v.object({ valid: v.literal(false) }),
15
+ );
16
+
17
+ /**
18
+ * Safe, leak-free projection of a token row for a management surface. NEVER
19
+ * includes `tokenHash` — only lifecycle metadata a UI may display.
20
+ */
21
+ export const tokenMetadata = v.object({
22
+ id: v.id("tokens"),
23
+ scope: v.string(),
24
+ resourceRef: v.optional(v.string()),
25
+ revoked: v.boolean(),
26
+ expiresAt: v.number(),
27
+ createdAt: v.number(),
28
+ });
@@ -0,0 +1,86 @@
1
+ // @vitest-environment jsdom
2
+
3
+ /**
4
+ * Tests for the optional `./react` front-tooling layer.
5
+ *
6
+ * Runs under jsdom (per-file pragma above; the global vitest env is
7
+ * edge-runtime). `convex/react` is mocked so `useTokens` is exercised in
8
+ * isolation — we assert it is a thin pass-through to `useQuery` and that its
9
+ * returned METADATA carries no secret/hash field (the no-leak contract).
10
+ */
11
+
12
+ import { renderHook } from "@testing-library/react";
13
+ import { describe, expect, test, vi } from "vitest";
14
+ import type { FunctionReference } from "convex/server";
15
+ import { useQuery } from "convex/react";
16
+ import { useTokens } from "./index.js";
17
+ import type { TokenMetadata } from "../client/types.js";
18
+
19
+ vi.mock("convex/react", () => ({ useQuery: vi.fn() }));
20
+
21
+ const useQueryMock = vi.mocked(useQuery);
22
+
23
+ type ListRef = FunctionReference<
24
+ "query",
25
+ "public",
26
+ { scope?: string; resourceRef: string },
27
+ TokenMetadata[]
28
+ >;
29
+
30
+ const listRef = "tokens.list" as unknown as ListRef;
31
+
32
+ function makeMetadata(): TokenMetadata {
33
+ return {
34
+ id: "tok_1",
35
+ scope: "global",
36
+ resourceRef: "user_1",
37
+ revoked: false,
38
+ expiresAt: 1_700_000_000_000,
39
+ createdAt: 1_699_000_000_000,
40
+ };
41
+ }
42
+
43
+ describe("useTokens", () => {
44
+ test("forwards the host list ref and args to useQuery, returns its data", () => {
45
+ const data = [makeMetadata()];
46
+ useQueryMock.mockReturnValue(data);
47
+
48
+ const args = { scope: "global", resourceRef: "user_1" };
49
+ const { result } = renderHook(() => useTokens(listRef, args));
50
+
51
+ expect(useQueryMock).toHaveBeenCalledTimes(1);
52
+ expect(useQueryMock).toHaveBeenCalledWith(listRef, args);
53
+ expect(result.current).toBe(data);
54
+ });
55
+
56
+ test("returns undefined while the query loads", () => {
57
+ useQueryMock.mockReturnValue(undefined);
58
+
59
+ const { result } = renderHook(() =>
60
+ useTokens(listRef, { resourceRef: "user_1" }),
61
+ );
62
+
63
+ expect(result.current).toBeUndefined();
64
+ });
65
+
66
+ test("returned metadata exposes no raw token or hash (no-leak contract)", () => {
67
+ const item = makeMetadata();
68
+ useQueryMock.mockReturnValue([item]);
69
+
70
+ const { result } = renderHook(() =>
71
+ useTokens(listRef, { resourceRef: "user_1" }),
72
+ );
73
+
74
+ const got = result.current?.[0];
75
+ expect(got).toBeDefined();
76
+ const keys = Object.keys(got as object);
77
+ expect(keys).not.toContain("tokenHash");
78
+ expect(keys).not.toContain("hash");
79
+ expect(keys).not.toContain("token");
80
+ expect(keys).not.toContain("rawToken");
81
+ expect(keys).not.toContain("secret");
82
+ expect(keys.sort()).toEqual(
83
+ ["createdAt", "expiresAt", "id", "resourceRef", "revoked", "scope"].sort(),
84
+ );
85
+ });
86
+ });
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Optional, tree-shakeable React front-tooling for `@vllnt/convex-tokens`.
3
+ *
4
+ * Thin reactive hook over `useQuery` from `convex/react`. It takes the HOST's
5
+ * re-exported `list` query reference plus its args — the component never imports
6
+ * the host `api`. `react` and `convex/react` are optional peer deps: a
7
+ * backend-only consumer pulls none of this code.
8
+ *
9
+ * NO-LEAK CONTRACT: this layer exposes ONLY non-secret token METADATA (id,
10
+ * scope, resourceRef, revoked, expiresAt, createdAt). It NEVER surfaces a raw
11
+ * token or its hash. Minting returns the raw secret exactly once, from the
12
+ * server-side `mint` mutation the host wraps — that mint-once raw value must
13
+ * never be persisted or logged, and it is intentionally NOT exposed by any hook
14
+ * here.
15
+ */
16
+
17
+ import type { FunctionReference } from "convex/server";
18
+ import { useQuery } from "convex/react";
19
+ import type { TokenMetadata } from "../client/types.js";
20
+
21
+ /**
22
+ * Reactive list of token METADATA for a management surface, scoped by an opaque
23
+ * host `resourceRef` (and an optional namespace). Wraps the `list` query's
24
+ * leak-free projection — never the hash, never a raw token.
25
+ *
26
+ * @param listRef - The host's re-exported `tokens.list` query reference.
27
+ * @param args - `{ scope?, resourceRef }`: optional namespace + the opaque
28
+ * host-owned reference to list tokens for.
29
+ * @returns The token metadata array, or `undefined` while the query loads.
30
+ */
31
+ export function useTokens(
32
+ listRef: FunctionReference<
33
+ "query",
34
+ "public",
35
+ { scope?: string; resourceRef: string },
36
+ TokenMetadata[]
37
+ >,
38
+ args: { scope?: string; resourceRef: string },
39
+ ): TokenMetadata[] | undefined {
40
+ return useQuery(listRef, args);
41
+ }
package/src/shared.ts ADDED
@@ -0,0 +1,98 @@
1
+ /** Shared constants + pure utilities used by both `client/` and `component/`. */
2
+
3
+ export const COMPONENT_NAME = "tokens";
4
+
5
+ /** Default namespace when the host does not scope a token. */
6
+ export const DEFAULT_SCOPE = "global";
7
+
8
+ /** Default token lifetime: 24 hours. */
9
+ export const DEFAULT_TTL_MS = 86_400_000;
10
+
11
+ /** Floor for a clamped TTL: 1 minute (a minted token always outlives a `Date.now()` test). */
12
+ export const MIN_TTL_MS = 60_000;
13
+
14
+ /** Default ceiling for a clamped TTL: 30 days. */
15
+ export const DEFAULT_MAX_TTL_MS = 2_592_000_000;
16
+
17
+ /** Default entropy for a generated raw token, in bytes (48 hex chars). */
18
+ export const DEFAULT_TOKEN_BYTES = 24;
19
+
20
+ /** Default retention for a revoked token before the prune sweep drops it: 24 hours. */
21
+ export const DEFAULT_REVOKED_RETENTION_MS = 86_400_000;
22
+
23
+ /** Max rows a single prune mutation deletes before self-rescheduling. */
24
+ export const PRUNE_BATCH = 256;
25
+
26
+ /** Hard ceiling on the `limit` argument of `list` queries. */
27
+ export const LIST_LIMIT_MAX = 1000;
28
+
29
+ /**
30
+ * Supported digest algorithms for {@link hashToken}. Fixed per mount — changing
31
+ * it invalidates every existing hash, so a deployment picks one and keeps it.
32
+ */
33
+ export type HashAlgo = "SHA-256" | "SHA-512";
34
+
35
+ /** Default digest algorithm. */
36
+ export const DEFAULT_HASH_ALGO: HashAlgo = "SHA-256";
37
+
38
+ /** Opaque host-supplied resource reference. Never assume its shape or source. */
39
+ export type ResourceRef = string;
40
+
41
+ /**
42
+ * Hex digest of `raw` under `algo` (default SHA-256). The component stores only
43
+ * this hash — the raw token is hashed by the client and never travels to or
44
+ * rests in the component. Uses Web Crypto (`crypto.subtle`), a global in
45
+ * edge-runtime and Node >=18.
46
+ *
47
+ * @param raw - The raw secret token to hash.
48
+ * @param algo - Digest algorithm; fixed per mount. Default `"SHA-256"`.
49
+ * @returns The lowercase hex digest.
50
+ */
51
+ export async function hashToken(
52
+ raw: string,
53
+ algo: HashAlgo = DEFAULT_HASH_ALGO,
54
+ ): Promise<string> {
55
+ const bytes = new TextEncoder().encode(raw);
56
+ const digest = await crypto.subtle.digest(algo, bytes);
57
+ return Array.from(new Uint8Array(digest))
58
+ .map((b) => b.toString(16).padStart(2, "0"))
59
+ .join("");
60
+ }
61
+
62
+ /**
63
+ * Generate a cryptographically random raw token as a hex string of `bytes`
64
+ * bytes (`2 * bytes` hex chars). Uses `crypto.getRandomValues` (a global).
65
+ *
66
+ * @param bytes - Entropy in bytes. Default {@link DEFAULT_TOKEN_BYTES}.
67
+ * @returns The hex-encoded random token.
68
+ */
69
+ export function generateToken(bytes = DEFAULT_TOKEN_BYTES): string {
70
+ const buf = new Uint8Array(bytes);
71
+ crypto.getRandomValues(buf);
72
+ return Array.from(buf)
73
+ .map((b) => b.toString(16).padStart(2, "0"))
74
+ .join("");
75
+ }
76
+
77
+ /**
78
+ * Clamp `ttlMs` into `[minMs, maxMs]`. A non-finite `ttlMs` (NaN / Infinity)
79
+ * falls back to `fallbackMs`; a non-finite `fallbackMs` falls back to `minMs`.
80
+ * The result is therefore always finite and >= `minMs`, so a malformed request
81
+ * can never produce a non-finite `expiresAt` (the expiry invariant holds).
82
+ *
83
+ * @param ttlMs - Requested lifetime in ms.
84
+ * @param minMs - Lower bound (also the ultimate finite fallback).
85
+ * @param maxMs - Upper bound.
86
+ * @param fallbackMs - Used when `ttlMs` is not finite.
87
+ * @returns The clamped, finite TTL.
88
+ */
89
+ export function clampTtl(
90
+ ttlMs: number,
91
+ minMs: number,
92
+ maxMs: number,
93
+ fallbackMs: number,
94
+ ): number {
95
+ const fallback = Number.isFinite(fallbackMs) ? fallbackMs : minMs;
96
+ const ttl = Number.isFinite(ttlMs) ? ttlMs : fallback;
97
+ return Math.min(maxMs, Math.max(minMs, ttl));
98
+ }
package/src/test.ts ADDED
@@ -0,0 +1,12 @@
1
+ import type { TestConvex } from "convex-test";
2
+ import schema from "./component/schema";
3
+
4
+ const modules = import.meta.glob("./component/**/*.ts");
5
+
6
+ /**
7
+ * Register this component with a `convex-test` instance so consuming apps can
8
+ * test integration: `import { register } from "@vllnt/convex-tokens/test"`.
9
+ */
10
+ export function register(t: TestConvex<typeof schema>, name = "tokens"): void {
11
+ t.registerComponent(name, schema, modules);
12
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Unit tests for shared pure utilities: {@link generateToken} and
3
+ * {@link hashToken}. These run in the global edge-runtime environment.
4
+ *
5
+ * Property-style coverage:
6
+ * - `generateToken(bytes)` always produces exactly `2 * bytes` lowercase hex chars.
7
+ * - `hashToken("")` does not throw; it returns a valid hex string.
8
+ */
9
+
10
+ import { describe, expect, test } from "vitest";
11
+ import { generateToken, hashToken } from "./shared.js";
12
+
13
+ describe("generateToken — property tests", () => {
14
+ test("default byte count yields 48 hex chars (24 bytes * 2)", async () => {
15
+ const token = generateToken();
16
+ expect(token).toHaveLength(48);
17
+ expect(token).toMatch(/^[0-9a-f]+$/);
18
+ });
19
+
20
+ const byteCounts = [1, 8, 16, 24, 32, 48, 64];
21
+ for (const bytes of byteCounts) {
22
+ test(`generateToken(${bytes}) yields exactly ${2 * bytes} lowercase hex chars`, () => {
23
+ const token = generateToken(bytes);
24
+ expect(token).toHaveLength(2 * bytes);
25
+ expect(token).toMatch(/^[0-9a-f]+$/);
26
+ });
27
+ }
28
+ });
29
+
30
+ describe("hashToken — edge cases", () => {
31
+ test("hashToken('') does not throw and returns a 64-char hex string (SHA-256)", async () => {
32
+ const hash = await hashToken("");
33
+ expect(hash).toHaveLength(64);
34
+ expect(hash).toMatch(/^[0-9a-f]+$/);
35
+ });
36
+
37
+ test("hashToken returns different digests for different inputs", async () => {
38
+ const h1 = await hashToken("abc");
39
+ const h2 = await hashToken("def");
40
+ expect(h1).not.toBe(h2);
41
+ });
42
+
43
+ test("hashToken SHA-512 returns 128-char hex string", async () => {
44
+ const hash = await hashToken("test", "SHA-512");
45
+ expect(hash).toHaveLength(128);
46
+ expect(hash).toMatch(/^[0-9a-f]+$/);
47
+ });
48
+ });