@vllnt/convex-tokens 0.1.0 → 0.1.1-canary.075894c
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/README.md +95 -33
- package/dist/component/crons.js +1 -1
- package/dist/component/crons.js.map +1 -1
- package/dist/component/mutations.d.ts.map +1 -1
- package/dist/component/mutations.js +41 -3
- package/dist/component/mutations.js.map +1 -1
- package/dist/component/queries.d.ts.map +1 -1
- package/dist/component/queries.js +11 -4
- package/dist/component/queries.js.map +1 -1
- package/dist/shared.d.ts +1 -0
- package/dist/shared.d.ts.map +1 -1
- package/dist/shared.js +9 -0
- package/dist/shared.js.map +1 -1
- package/package.json +32 -21
- package/src/component/crons.ts +1 -1
- package/src/component/mutations.ts +41 -3
- package/src/component/queries.ts +11 -4
- package/src/shared.ts +10 -0
- package/src/test.ts +2 -1
- package/src/component/component.test.ts +0 -75
- package/src/react/index.test.tsx +0 -86
- package/src/unit.test.ts +0 -48
package/README.md
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
<!-- Badges -->
|
|
2
|
+
|
|
2
3
|
[](https://www.convex.dev/components)
|
|
3
4
|
[](https://www.npmjs.com/package/@vllnt/convex-tokens)
|
|
4
5
|
[](https://github.com/vllnt/convex-tokens/actions/workflows/ci.yml)
|
|
@@ -6,7 +7,9 @@
|
|
|
6
7
|
|
|
7
8
|
# @vllnt/convex-tokens
|
|
8
9
|
|
|
9
|
-
Hashed-secret token primitive with mint-once, TTL, revoke and scope, as a Convex
|
|
10
|
+
Hashed-secret token primitive with mint-once, TTL, revoke and scope, as a Convex
|
|
11
|
+
component — mint a secret against an opaque `resourceRef`, return the raw value
|
|
12
|
+
once, and store only its SHA-256 hash.
|
|
10
13
|
|
|
11
14
|
```ts
|
|
12
15
|
const tokens = new Tokens(components.tokens);
|
|
@@ -16,13 +19,18 @@ const result = await tokens.validate(ctx, rawToken); // { valid: true, resourceR
|
|
|
16
19
|
|
|
17
20
|
## Features
|
|
18
21
|
|
|
19
|
-
- **Mint-once** — the raw token is returned a single time and never persisted;
|
|
20
|
-
|
|
21
|
-
- **
|
|
22
|
-
|
|
22
|
+
- **Mint-once** — the raw token is returned a single time and never persisted;
|
|
23
|
+
only its digest rests in the component.
|
|
24
|
+
- **Hash-at-rest** — a leaked DB row can't be replayed; digest is `SHA-256` by
|
|
25
|
+
default, `SHA-512` configurable, fixed per mount.
|
|
26
|
+
- **Server-sourced time** — `expiresAt` and validate-time `now` come from the
|
|
27
|
+
server clock; expiry can't be spoofed.
|
|
28
|
+
- **TTL with clamp** — every token expires; a requested `ttlMs` is clamped
|
|
29
|
+
server-side into `[MIN_TTL_MS, maxTtlMs]`.
|
|
23
30
|
- **Revoke** — invalidate a token before it expires, via a transition contract.
|
|
24
31
|
- **Scopes** — global by default, or namespace per tenant / purpose / locale.
|
|
25
|
-
- **Self-pruning cron + safe management surface** — sweeps expired/stale-revoked
|
|
32
|
+
- **Self-pruning cron + safe management surface** — sweeps expired/stale-revoked
|
|
33
|
+
tokens; `list`/`getMetadata` never return the hash.
|
|
26
34
|
|
|
27
35
|
## Installation
|
|
28
36
|
|
|
@@ -30,7 +38,10 @@ const result = await tokens.validate(ctx, rawToken); // { valid: true, resourceR
|
|
|
30
38
|
pnpm add @vllnt/convex-tokens
|
|
31
39
|
```
|
|
32
40
|
|
|
33
|
-
|
|
41
|
+
Requires `convex@^1.45.0`; React `>=18` is optional for `./react` only. The
|
|
42
|
+
command installs the latest stable release; use `@vllnt/convex-tokens@canary`
|
|
43
|
+
for the newest pre-release build from `main`, and pin a resolved canary version
|
|
44
|
+
for reproducible installs.
|
|
34
45
|
|
|
35
46
|
## Usage
|
|
36
47
|
|
|
@@ -45,7 +56,7 @@ export default app;
|
|
|
45
56
|
```
|
|
46
57
|
|
|
47
58
|
```ts
|
|
48
|
-
// convex/
|
|
59
|
+
// convex/tokens.ts — expose only the authenticated caller's own tokens.
|
|
49
60
|
import { components } from "./_generated/api";
|
|
50
61
|
import { mutation, query } from "./_generated/server";
|
|
51
62
|
import { v } from "convex/values";
|
|
@@ -54,50 +65,82 @@ import { Tokens } from "@vllnt/convex-tokens";
|
|
|
54
65
|
const tokens = new Tokens(components.tokens);
|
|
55
66
|
|
|
56
67
|
export const issue = mutation({
|
|
57
|
-
args: {
|
|
58
|
-
//
|
|
59
|
-
handler: (ctx
|
|
68
|
+
args: {},
|
|
69
|
+
// Show the raw token once; do not persist or log it.
|
|
70
|
+
handler: async (ctx) => {
|
|
71
|
+
const identity = await ctx.auth.getUserIdentity();
|
|
72
|
+
if (!identity) throw new Error("Unauthenticated");
|
|
73
|
+
return tokens.mint(ctx, { resourceRef: identity.tokenIdentifier });
|
|
74
|
+
},
|
|
60
75
|
});
|
|
61
76
|
|
|
62
|
-
export const
|
|
63
|
-
args: {
|
|
64
|
-
handler: (ctx, {
|
|
77
|
+
export const list = query({
|
|
78
|
+
args: { scope: v.optional(v.string()), resourceRef: v.string() },
|
|
79
|
+
handler: async (ctx, { scope, resourceRef }) => {
|
|
80
|
+
const identity = await ctx.auth.getUserIdentity();
|
|
81
|
+
if (
|
|
82
|
+
!identity ||
|
|
83
|
+
resourceRef !== identity.tokenIdentifier ||
|
|
84
|
+
(scope !== undefined && scope !== "global")
|
|
85
|
+
) {
|
|
86
|
+
throw new Error("Forbidden");
|
|
87
|
+
}
|
|
88
|
+
return tokens.list(ctx, { scope: "global", resourceRef });
|
|
89
|
+
},
|
|
65
90
|
});
|
|
66
91
|
```
|
|
67
92
|
|
|
68
93
|
## API Reference
|
|
69
94
|
|
|
70
|
-
| Method
|
|
71
|
-
|
|
72
|
-
| `mint(ctx, { scope?, resourceRef?, ttlMs? })` | mutation | `{ token, id }` (raw shown once; TTL clamped server-side)
|
|
73
|
-
| `validate(ctx, rawToken, scope?)`
|
|
74
|
-
| `revoke(ctx, rawToken, scope?)`
|
|
75
|
-
| `list(ctx, { scope?, resourceRef?, limit? })` | query
|
|
76
|
-
| `getMetadata(ctx, id)`
|
|
77
|
-
| `prune(ctx, before?)`
|
|
95
|
+
| Method | Kind | Result |
|
|
96
|
+
| --------------------------------------------- | -------- | ----------------------------------------------------------- |
|
|
97
|
+
| `mint(ctx, { scope?, resourceRef?, ttlMs? })` | mutation | `{ token, id }` (raw shown once; TTL clamped server-side) |
|
|
98
|
+
| `validate(ctx, rawToken, scope?)` | query | `{ valid: true, resourceRef? } \| { valid: false }` |
|
|
99
|
+
| `revoke(ctx, rawToken, scope?)` | mutation | `boolean` (`true` = transitioned to revoked this call) |
|
|
100
|
+
| `list(ctx, { scope?, resourceRef?, limit? })` | query | `TokenMetadata[]` (never the hash; `limit` clamped to 1000) |
|
|
101
|
+
| `getMetadata(ctx, id)` | query | `TokenMetadata \| null` (never the hash) |
|
|
102
|
+
| `prune(ctx, before?)` | mutation | `number` (deleted in a bounded batch) |
|
|
78
103
|
|
|
79
|
-
Full reference: [docs/API.md](docs/API.md) — including client options
|
|
104
|
+
Full reference: [docs/API.md](docs/API.md) — including client options
|
|
105
|
+
(`defaultScope`, `defaultTtlMs`, `maxTtlMs`, `hashAlgo`, …) and the error codes.
|
|
80
106
|
|
|
81
107
|
## React
|
|
82
108
|
|
|
83
|
-
Optional, tree-shakeable front-tooling at `@vllnt/convex-tokens/react`; `react`
|
|
109
|
+
Optional, tree-shakeable front-tooling at `@vllnt/convex-tokens/react`; `react`
|
|
110
|
+
is optional, but `convex` is required. **No-leak:** hooks expose only token
|
|
111
|
+
metadata — never a raw token or hash. Pass the host's own re-exported `list`
|
|
112
|
+
query ref.
|
|
84
113
|
|
|
85
114
|
```tsx
|
|
86
115
|
import { useTokens } from "@vllnt/convex-tokens/react";
|
|
87
116
|
import { api } from "./convex/_generated/api";
|
|
88
117
|
|
|
89
|
-
|
|
118
|
+
// Inside a React component; resourceRef is the caller's tokenIdentifier.
|
|
119
|
+
const tokens = useTokens(api.tokens.list, { resourceRef }); // TokenMetadata[] | undefined
|
|
90
120
|
```
|
|
91
121
|
|
|
92
|
-
| Hook
|
|
93
|
-
|
|
122
|
+
| Hook | Wraps | Returns |
|
|
123
|
+
| --------------------------------------------- | ------------------- | ---------------------------------------------- |
|
|
94
124
|
| `useTokens(listRef, { scope?, resourceRef })` | host's `list` query | `TokenMetadata[] \| undefined` (metadata only) |
|
|
95
125
|
|
|
96
126
|
## Security
|
|
97
127
|
|
|
98
|
-
- Auth-agnostic — the host resolves identity and passes an opaque `resourceRef`;
|
|
99
|
-
|
|
100
|
-
-
|
|
128
|
+
- Auth-agnostic — the host resolves identity and passes an opaque `resourceRef`;
|
|
129
|
+
the component never authenticates.
|
|
130
|
+
- Hash-at-rest — the server-side `Tokens` client generates and hashes the raw
|
|
131
|
+
token (Web Crypto, SHA-256 by default) before calling the component. Only the
|
|
132
|
+
digest is stored; never log or persist the returned raw secret.
|
|
133
|
+
- Metadata is not automatically authorized: gate `list` and `getMetadata` in the
|
|
134
|
+
host, including resource and scope access. Avoid exposing a public validation
|
|
135
|
+
oracle for other subjects' tokens.
|
|
136
|
+
- Single use: `revoke` runs in one transaction, so of any number of concurrent
|
|
137
|
+
calls for one token exactly one returns `true`. To redeem a token once, call
|
|
138
|
+
`revoke` and act only on `true`; do not rely on a prior `validate`. `revoke`
|
|
139
|
+
does not check expiry, so reject an expired token first (`validate`) if that
|
|
140
|
+
matters.
|
|
141
|
+
- Time is server-sourced (expiry can't be forged), `validate` returns a
|
|
142
|
+
discriminated union, and the management surface (`list`, `getMetadata`) never
|
|
143
|
+
returns the hash.
|
|
101
144
|
|
|
102
145
|
See [docs/API.md](docs/API.md).
|
|
103
146
|
|
|
@@ -108,7 +151,24 @@ pnpm test # single run
|
|
|
108
151
|
pnpm test:coverage # enforced 100% on covered files
|
|
109
152
|
```
|
|
110
153
|
|
|
111
|
-
Tests run against the real component runtime via `convex-test`
|
|
154
|
+
Tests run against the real component runtime via `convex-test`
|
|
155
|
+
(`@edge-runtime/vm`), not mocks.
|
|
156
|
+
|
|
157
|
+
### Testing your app
|
|
158
|
+
|
|
159
|
+
`@vllnt/convex-tokens/test` exports `register(t, name = "tokens")` to mount the
|
|
160
|
+
component in a `convex-test` instance. It needs `convex-test` and `vitest` (with
|
|
161
|
+
Vite's `import.meta.glob`) in the consuming app:
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
/// <reference types="vite/client" />
|
|
165
|
+
import { convexTest } from "convex-test";
|
|
166
|
+
import { register } from "@vllnt/convex-tokens/test";
|
|
167
|
+
import schema from "./schema";
|
|
168
|
+
|
|
169
|
+
const t = convexTest(schema, import.meta.glob("./**/*.ts"));
|
|
170
|
+
register(t);
|
|
171
|
+
```
|
|
112
172
|
|
|
113
173
|
## Contributing
|
|
114
174
|
|
|
@@ -116,9 +176,11 @@ See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
|
116
176
|
|
|
117
177
|
## Author
|
|
118
178
|
|
|
119
|
-
Built by [bntvllnt](https://github.com/bntvllnt) ·
|
|
179
|
+
Built by [bntvllnt](https://github.com/bntvllnt) ·
|
|
180
|
+
[bntvllnt.com](https://bntvllnt.com) · [X @bntvllnt](https://x.com/bntvllnt)
|
|
120
181
|
|
|
121
|
-
Part of the [@vllnt](https://github.com/vllnt) Convex component fleet —
|
|
182
|
+
Part of the [@vllnt](https://github.com/vllnt) Convex component fleet —
|
|
183
|
+
[vllnt.com](https://vllnt.com)
|
|
122
184
|
|
|
123
185
|
If this is useful, [sponsor the work](https://github.com/sponsors/bntvllnt).
|
|
124
186
|
|
package/dist/component/crons.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { cronJobs } from "convex/server";
|
|
2
|
-
import { internal } from "./_generated/api";
|
|
2
|
+
import { internal } from "./_generated/api.js";
|
|
3
3
|
/**
|
|
4
4
|
* Internal cron that sweeps expired and stale-revoked tokens daily. The cadence
|
|
5
5
|
* is fixed at the component layer (Convex crons are static); a mount that needs
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crons.js","sourceRoot":"","sources":["../../src/component/crons.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"crons.js","sourceRoot":"","sources":["../../src/component/crons.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAE/C;;;;;;GAMG;AACH,MAAM,KAAK,GAAG,QAAQ,EAAE,CAAC;AAEzB,KAAK,CAAC,QAAQ,CACZ,yCAAyC,EACzC,EAAE,KAAK,EAAE,EAAE,EAAE,EACb,QAAQ,CAAC,SAAS,CAAC,YAAY,CAChC,CAAC;AAEF,eAAe,KAAK,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutations.d.ts","sourceRoot":"","sources":["../../src/component/mutations.ts"],"names":[],"mappings":"AAwBA;;;;;;GAMG;AACH,eAAO,MAAM,IAAI;;;;;;;
|
|
1
|
+
{"version":3,"file":"mutations.d.ts","sourceRoot":"","sources":["../../src/component/mutations.ts"],"names":[],"mappings":"AAwBA;;;;;;GAMG;AACH,eAAO,MAAM,IAAI;;;;;;;wDAiEf,CAAC;AAEH;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,MAAM;;;oBAcjB,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,KAAK;;mBAmBhB,CAAC;AAEH;;;;;GAKG;AACH,eAAO,MAAM,YAAY,2EAmCvB,CAAC"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { v } from "convex/values";
|
|
2
2
|
import { ConvexError } from "convex/values";
|
|
3
|
-
import { internalMutation, mutation } from "./_generated/server";
|
|
4
|
-
import { internal } from "./_generated/api";
|
|
5
|
-
import { clampTtl, DEFAULT_REVOKED_RETENTION_MS, MIN_TTL_MS, PRUNE_BATCH, } from "../shared";
|
|
3
|
+
import { internalMutation, mutation } from "./_generated/server.js";
|
|
4
|
+
import { internal } from "./_generated/api.js";
|
|
5
|
+
import { clampTtl, DEFAULT_REVOKED_RETENTION_MS, MIN_TTL_MS, PRUNE_BATCH, } from "../shared.js";
|
|
6
6
|
/**
|
|
7
7
|
* Minimum length of a valid hex digest (SHA-256 = 64 hex chars).
|
|
8
8
|
*
|
|
@@ -32,6 +32,26 @@ export const mint = mutation({
|
|
|
32
32
|
},
|
|
33
33
|
returns: v.id("tokens"),
|
|
34
34
|
handler: async (ctx, args) => {
|
|
35
|
+
if (args.scope === "") {
|
|
36
|
+
throw new ConvexError({
|
|
37
|
+
code: "INVALID_SCOPE",
|
|
38
|
+
message: "scope must be a non-empty string.",
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
if (args.resourceRef === "") {
|
|
42
|
+
throw new ConvexError({
|
|
43
|
+
code: "INVALID_RESOURCE_REF",
|
|
44
|
+
message: "resourceRef must be omitted or a non-empty string.",
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
// `!(x > 0)` also rejects NaN, which would otherwise yield a NaN `expiresAt`
|
|
48
|
+
// (never `<= now`) and so a token that never expires.
|
|
49
|
+
if (!(args.maxTtlMs > 0)) {
|
|
50
|
+
throw new ConvexError({
|
|
51
|
+
code: "INVALID_TTL",
|
|
52
|
+
message: "maxTtlMs must be a number greater than 0.",
|
|
53
|
+
});
|
|
54
|
+
}
|
|
35
55
|
const isPlausibleHash = args.tokenHash.length >= MIN_HASH_LENGTH &&
|
|
36
56
|
HASH_PATTERN.test(args.tokenHash);
|
|
37
57
|
if (!isPlausibleHash) {
|
|
@@ -41,6 +61,18 @@ export const mint = mutation({
|
|
|
41
61
|
"Use client.hashToken() to produce a valid hash.",
|
|
42
62
|
});
|
|
43
63
|
}
|
|
64
|
+
const existing = await ctx.db
|
|
65
|
+
.query("tokens")
|
|
66
|
+
.withIndex("by_hash", (q) => q.eq("tokenHash", args.tokenHash))
|
|
67
|
+
.first();
|
|
68
|
+
if (existing !== null) {
|
|
69
|
+
// Lookups use `.unique()`; a second row with the same hash would make
|
|
70
|
+
// `validate` and `revoke` throw for that token.
|
|
71
|
+
throw new ConvexError({
|
|
72
|
+
code: "DUPLICATE_TOKEN_HASH",
|
|
73
|
+
message: "A token with this hash already exists.",
|
|
74
|
+
});
|
|
75
|
+
}
|
|
44
76
|
const ttl = clampTtl(args.ttlMs, MIN_TTL_MS, args.maxTtlMs, args.defaultTtlMs);
|
|
45
77
|
const now = Date.now();
|
|
46
78
|
return await ctx.db.insert("tokens", {
|
|
@@ -91,6 +123,12 @@ export const prune = mutation({
|
|
|
91
123
|
args: { before: v.number() },
|
|
92
124
|
returns: v.number(),
|
|
93
125
|
handler: async (ctx, args) => {
|
|
126
|
+
if (Number.isNaN(args.before)) {
|
|
127
|
+
throw new ConvexError({
|
|
128
|
+
code: "INVALID_BEFORE",
|
|
129
|
+
message: "before must be a number.",
|
|
130
|
+
});
|
|
131
|
+
}
|
|
94
132
|
const expired = await ctx.db
|
|
95
133
|
.query("tokens")
|
|
96
134
|
.withIndex("by_expires", (q) => q.lt("expiresAt", args.before))
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutations.js","sourceRoot":"","sources":["../../src/component/mutations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,eAAe,CAAC;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"mutations.js","sourceRoot":"","sources":["../../src/component/mutations.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,eAAe,CAAC;AAClC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AACpE,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EACL,QAAQ,EACR,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A4B,CAAC;YACzD,MAAM,YAAY,GAAG,MAAM,GAAG,CAAC,EAAE;iBAC9B,KAAK,CAAC,QAAQ,CAAC;iBACf,SAAS,CAAC,oBAAoB,EAAE,CAAC,CAAC,EAAE,EAAE,CACrC,CAAC,CAAC,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,EAAE,CAAC,WAAW,EAAE,aAAa,CAAC,CACrD;iBACA,IAAI,CAAC,SAAS,CAAC,CAAC;YACnB,KAAK,MAAM,GAAG,IAAI,YAAY,EAAE,CAAC;gBAC/B,MAAM,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,QAAQ,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;YACzC,CAAC;YACD,cAAc,GAAG,YAAY,CAAC,MAAM,CAAC;QACvC,CAAC;QAED,IAAI,OAAO,CAAC,MAAM,GAAG,cAAc,KAAK,WAAW,EAAE,CAAC;YACpD,MAAM,GAAG,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAE,QAAQ,CAAC,SAAS,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;QACvE,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;CACF,CAAC,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queries.d.ts","sourceRoot":"","sources":["../../src/component/queries.ts"],"names":[],"mappings":"AAKA;;;;;GAKG;AACH,eAAO,MAAM,QAAQ;;;;;;;;;GAmBnB,CAAC;AAEH;;;;;;;GAOG;AACH,eAAO,MAAM,IAAI;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"queries.d.ts","sourceRoot":"","sources":["../../src/component/queries.ts"],"names":[],"mappings":"AAKA;;;;;GAKG;AACH,eAAO,MAAM,QAAQ;;;;;;;;;GAmBnB,CAAC;AAEH;;;;;;;GAOG;AACH,eAAO,MAAM,IAAI;;;;;;;;;;;KAiCf,CAAC;AAEH;;;GAGG;AACH,eAAO,MAAM,WAAW;;;;;;;;;UAiBtB,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { v } from "convex/values";
|
|
2
|
-
import { query } from "./_generated/server";
|
|
3
|
-
import { tokenMetadata, validateResult } from "./validators";
|
|
1
|
+
import { ConvexError, v } from "convex/values";
|
|
2
|
+
import { query } from "./_generated/server.js";
|
|
3
|
+
import { tokenMetadata, validateResult } from "./validators.js";
|
|
4
4
|
import { LIST_LIMIT_MAX } from "../shared.js";
|
|
5
5
|
/**
|
|
6
6
|
* Validate a token by its hash. Reads the current time from `Date.now()` INSIDE
|
|
@@ -42,7 +42,14 @@ export const list = query({
|
|
|
42
42
|
},
|
|
43
43
|
returns: v.array(tokenMetadata),
|
|
44
44
|
handler: async (ctx, args) => {
|
|
45
|
-
const
|
|
45
|
+
const requested = args.limit ?? 100;
|
|
46
|
+
if (!Number.isInteger(requested) || requested < 0) {
|
|
47
|
+
throw new ConvexError({
|
|
48
|
+
code: "INVALID_LIMIT",
|
|
49
|
+
message: "limit must be a non-negative integer.",
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
const limit = Math.min(requested, LIST_LIMIT_MAX);
|
|
46
53
|
const rows = await ctx.db
|
|
47
54
|
.query("tokens")
|
|
48
55
|
.withIndex("by_scope_resource", (q) => args.resourceRef === undefined
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queries.js","sourceRoot":"","sources":["../../src/component/queries.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"queries.js","sourceRoot":"","sources":["../../src/component/queries.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,CAAC,EAAE,MAAM,eAAe,CAAC;AAC/C,OAAO,EAAE,KAAK,EAAE,MAAM,wBAAwB,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AA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C,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE;IAC5B,OAAO,EAAE,CAAC,CAAC,KAAK,CAAC,aAAa,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACzC,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC3B,MAAM,GAAG,GAAG,MAAM,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC;QAChD,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;YACjB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO;YACL,EAAE,EAAE,GAAG,CAAC,GAAG;YACX,KAAK,EAAE,GAAG,CAAC,KAAK;YAChB,WAAW,EAAE,GAAG,CAAC,WAAW;YAC5B,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,SAAS,EAAE,GAAG,CAAC,SAAS;YACxB,SAAS,EAAE,GAAG,CAAC,SAAS;SACzB,CAAC;IACJ,CAAC;CACF,CAAC,CAAC"}
|
package/dist/shared.d.ts
CHANGED
|
@@ -42,6 +42,7 @@ export declare function hashToken(raw: string, algo?: HashAlgo): Promise<string>
|
|
|
42
42
|
*
|
|
43
43
|
* @param bytes - Entropy in bytes. Default {@link DEFAULT_TOKEN_BYTES}.
|
|
44
44
|
* @returns The hex-encoded random token.
|
|
45
|
+
* @throws ConvexError `INVALID_TOKEN_BYTES` when `bytes` is not an integer >= 1.
|
|
45
46
|
*/
|
|
46
47
|
export declare function generateToken(bytes?: number): string;
|
|
47
48
|
/**
|
package/dist/shared.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA,iFAAiF;
|
|
1
|
+
{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA,iFAAiF;AAIjF,eAAO,MAAM,cAAc,WAAW,CAAC;AAEvC,8DAA8D;AAC9D,eAAO,MAAM,aAAa,WAAW,CAAC;AAEtC,wCAAwC;AACxC,eAAO,MAAM,cAAc,WAAa,CAAC;AAEzC,8FAA8F;AAC9F,eAAO,MAAM,UAAU,QAAS,CAAC;AAEjC,kDAAkD;AAClD,eAAO,MAAM,kBAAkB,aAAgB,CAAC;AAEhD,0EAA0E;AAC1E,eAAO,MAAM,mBAAmB,KAAK,CAAC;AAEtC,uFAAuF;AACvF,eAAO,MAAM,4BAA4B,WAAa,CAAC;AAEvD,yEAAyE;AACzE,eAAO,MAAM,WAAW,MAAM,CAAC;AAE/B,8DAA8D;AAC9D,eAAO,MAAM,cAAc,OAAO,CAAC;AAEnC;;;GAGG;AACH,MAAM,MAAM,QAAQ,GAAG,SAAS,GAAG,SAAS,CAAC;AAE7C,gCAAgC;AAChC,eAAO,MAAM,iBAAiB,EAAE,QAAoB,CAAC;AAErD,iFAAiF;AACjF,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC;AAEjC;;;;;;;;;GASG;AACH,wBAAsB,SAAS,CAC7B,GAAG,EAAE,MAAM,EACX,IAAI,GAAE,QAA4B,GACjC,OAAO,CAAC,MAAM,CAAC,CAMjB;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,KAAK,SAAsB,GAAG,MAAM,CAajE;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,QAAQ,CACtB,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,UAAU,EAAE,MAAM,GACjB,MAAM,CAIR"}
|
package/dist/shared.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/** Shared constants + pure utilities used by both `client/` and `component/`. */
|
|
2
|
+
import { ConvexError } from "convex/values";
|
|
2
3
|
export const COMPONENT_NAME = "tokens";
|
|
3
4
|
/** Default namespace when the host does not scope a token. */
|
|
4
5
|
export const DEFAULT_SCOPE = "global";
|
|
@@ -41,8 +42,16 @@ export async function hashToken(raw, algo = DEFAULT_HASH_ALGO) {
|
|
|
41
42
|
*
|
|
42
43
|
* @param bytes - Entropy in bytes. Default {@link DEFAULT_TOKEN_BYTES}.
|
|
43
44
|
* @returns The hex-encoded random token.
|
|
45
|
+
* @throws ConvexError `INVALID_TOKEN_BYTES` when `bytes` is not an integer >= 1.
|
|
44
46
|
*/
|
|
45
47
|
export function generateToken(bytes = DEFAULT_TOKEN_BYTES) {
|
|
48
|
+
// `new Uint8Array(NaN)` and `(0)` are empty: that would mint the empty token.
|
|
49
|
+
if (!Number.isInteger(bytes) || bytes < 1) {
|
|
50
|
+
throw new ConvexError({
|
|
51
|
+
code: "INVALID_TOKEN_BYTES",
|
|
52
|
+
message: "tokenBytes must be an integer >= 1.",
|
|
53
|
+
});
|
|
54
|
+
}
|
|
46
55
|
const buf = new Uint8Array(bytes);
|
|
47
56
|
crypto.getRandomValues(buf);
|
|
48
57
|
return Array.from(buf)
|
package/dist/shared.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared.js","sourceRoot":"","sources":["../src/shared.ts"],"names":[],"mappings":"AAAA,iFAAiF;AAEjF,MAAM,CAAC,MAAM,cAAc,GAAG,QAAQ,CAAC;AAEvC,8DAA8D;AAC9D,MAAM,CAAC,MAAM,aAAa,GAAG,QAAQ,CAAC;AAEtC,wCAAwC;AACxC,MAAM,CAAC,MAAM,cAAc,GAAG,UAAU,CAAC;AAEzC,8FAA8F;AAC9F,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,CAAC;AAEjC,kDAAkD;AAClD,MAAM,CAAC,MAAM,kBAAkB,GAAG,aAAa,CAAC;AAEhD,0EAA0E;AAC1E,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAEtC,uFAAuF;AACvF,MAAM,CAAC,MAAM,4BAA4B,GAAG,UAAU,CAAC;AAEvD,yEAAyE;AACzE,MAAM,CAAC,MAAM,WAAW,GAAG,GAAG,CAAC;AAE/B,8DAA8D;AAC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AE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;SAC3C,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,QAAQ,CACtB,KAAa,EACb,KAAa,EACb,KAAa,EACb,UAAkB;IAElB,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC;IAClE,MAAM,GAAG,GAAG,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC;IACtD,OAAO,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC;AAC/C,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vllnt/convex-tokens",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1-canary.075894c",
|
|
4
4
|
"description": "Hashed-secret token primitive with mint-once, TTL, revoke and scope, as a Convex component",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
|
-
"packageManager": "pnpm@
|
|
7
|
+
"packageManager": "pnpm@10.34.8",
|
|
8
8
|
"files": [
|
|
9
9
|
"dist",
|
|
10
|
-
"src"
|
|
10
|
+
"src",
|
|
11
|
+
"!src/**/*.test.*"
|
|
11
12
|
],
|
|
12
13
|
"exports": {
|
|
13
14
|
"./package.json": "./package.json",
|
|
@@ -41,17 +42,14 @@
|
|
|
41
42
|
"build": "tsc --project ./tsconfig.build.json",
|
|
42
43
|
"build:codegen": "pnpm codegen && pnpm build",
|
|
43
44
|
"build:clean": "rm -rf dist *.tsbuildinfo && pnpm build:codegen",
|
|
44
|
-
"typecheck": "tsc --noEmit",
|
|
45
|
-
"typecheck:ci": "tsc --noEmit --project tsconfig.ci.json",
|
|
46
|
-
"lint": "pnpm check:agents && eslint .",
|
|
45
|
+
"typecheck": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck.tsbuildinfo",
|
|
46
|
+
"typecheck:ci": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck-ci.tsbuildinfo --project tsconfig.ci.json",
|
|
47
|
+
"lint": "pnpm check:agents && eslint --cache --cache-location node_modules/.cache/eslint/ .",
|
|
47
48
|
"test": "vitest run --passWithNoTests",
|
|
48
49
|
"test:watch": "vitest --typecheck --clearScreen false",
|
|
49
50
|
"test:coverage": "vitest run --coverage --coverage.reporter=text",
|
|
50
51
|
"generate:llms": "node scripts/generate-llms.mjs",
|
|
51
52
|
"preversion": "pnpm install --frozen-lockfile && pnpm build && pnpm test:coverage && pnpm typecheck && pnpm generate:llms",
|
|
52
|
-
"prepublishOnly": "npm whoami || npm login",
|
|
53
|
-
"alpha": "npm version prerelease --preid alpha && npm publish --tag alpha && git push --follow-tags",
|
|
54
|
-
"release": "npm version patch && npm publish && git push --follow-tags",
|
|
55
53
|
"check:agents": "node -e \"const f=require('node:fs');if(!f.existsSync('AGENTS.md')||f.existsSync('CLAUDE.md')||f.existsSync('.claude'))process.exit(1)\"",
|
|
56
54
|
"codegen": "pnpm convex codegen --component-dir ./src/component"
|
|
57
55
|
},
|
|
@@ -67,22 +65,22 @@
|
|
|
67
65
|
"devDependencies": {
|
|
68
66
|
"@edge-runtime/vm": "^5.0.0",
|
|
69
67
|
"@testing-library/react": "^16.3.3",
|
|
70
|
-
"@types/react": "^19.
|
|
71
|
-
"@types/react-dom": "^19.
|
|
68
|
+
"@types/react": "^19.3.0",
|
|
69
|
+
"@types/react-dom": "^19.3.0",
|
|
72
70
|
"@typescript/native": "npm:typescript@7.0.2",
|
|
73
|
-
"@vitest/coverage-v8": "^
|
|
71
|
+
"@vitest/coverage-v8": "^5.0.5",
|
|
74
72
|
"@vllnt/eslint-config": "2.0.0",
|
|
75
73
|
"@vllnt/typescript": "2.0.0",
|
|
76
|
-
"convex": "^1.
|
|
77
|
-
"convex-test": "^0.0.
|
|
74
|
+
"convex": "^1.48.0",
|
|
75
|
+
"convex-test": "^0.0.65",
|
|
78
76
|
"eslint": "^9.39.5",
|
|
79
|
-
"jsdom": "^
|
|
80
|
-
"prettier": "^3.9.
|
|
81
|
-
"react": "^19.
|
|
82
|
-
"react-dom": "^19.
|
|
77
|
+
"jsdom": "^30.1.3",
|
|
78
|
+
"prettier": "^3.9.10",
|
|
79
|
+
"react": "^19.3.1",
|
|
80
|
+
"react-dom": "^19.3.1",
|
|
83
81
|
"typescript": "npm:@typescript/typescript6@^6.0.2",
|
|
84
|
-
"vite": "^8.
|
|
85
|
-
"vitest": "^
|
|
82
|
+
"vite": "^8.3.5",
|
|
83
|
+
"vitest": "^5.0.5"
|
|
86
84
|
},
|
|
87
85
|
"homepage": "https://github.com/vllnt/convex-tokens#readme",
|
|
88
86
|
"bugs": {
|
|
@@ -111,5 +109,18 @@
|
|
|
111
109
|
"convex",
|
|
112
110
|
"convex-component",
|
|
113
111
|
"tokens"
|
|
114
|
-
]
|
|
112
|
+
],
|
|
113
|
+
"pnpm": {
|
|
114
|
+
"overrides": {
|
|
115
|
+
"deepmerge-ts@<8.0.0": "8.0.2",
|
|
116
|
+
"handlebars@<4.7.10": "4.7.10"
|
|
117
|
+
},
|
|
118
|
+
"minimumReleaseAge": 10080,
|
|
119
|
+
"minimumReleaseAgeExclude": [
|
|
120
|
+
"@vllnt/*"
|
|
121
|
+
],
|
|
122
|
+
"ignoredBuiltDependencies": [
|
|
123
|
+
"esbuild"
|
|
124
|
+
]
|
|
125
|
+
}
|
|
115
126
|
}
|
package/src/component/crons.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { v } from "convex/values";
|
|
2
2
|
import { ConvexError } from "convex/values";
|
|
3
|
-
import { internalMutation, mutation } from "./_generated/server";
|
|
4
|
-
import { internal } from "./_generated/api";
|
|
3
|
+
import { internalMutation, mutation } from "./_generated/server.js";
|
|
4
|
+
import { internal } from "./_generated/api.js";
|
|
5
5
|
import {
|
|
6
6
|
clampTtl,
|
|
7
7
|
DEFAULT_REVOKED_RETENTION_MS,
|
|
8
8
|
MIN_TTL_MS,
|
|
9
9
|
PRUNE_BATCH,
|
|
10
|
-
} from "../shared";
|
|
10
|
+
} from "../shared.js";
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Minimum length of a valid hex digest (SHA-256 = 64 hex chars).
|
|
@@ -40,6 +40,26 @@ export const mint = mutation({
|
|
|
40
40
|
},
|
|
41
41
|
returns: v.id("tokens"),
|
|
42
42
|
handler: async (ctx, args) => {
|
|
43
|
+
if (args.scope === "") {
|
|
44
|
+
throw new ConvexError({
|
|
45
|
+
code: "INVALID_SCOPE",
|
|
46
|
+
message: "scope must be a non-empty string.",
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
if (args.resourceRef === "") {
|
|
50
|
+
throw new ConvexError({
|
|
51
|
+
code: "INVALID_RESOURCE_REF",
|
|
52
|
+
message: "resourceRef must be omitted or a non-empty string.",
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
// `!(x > 0)` also rejects NaN, which would otherwise yield a NaN `expiresAt`
|
|
56
|
+
// (never `<= now`) and so a token that never expires.
|
|
57
|
+
if (!(args.maxTtlMs > 0)) {
|
|
58
|
+
throw new ConvexError({
|
|
59
|
+
code: "INVALID_TTL",
|
|
60
|
+
message: "maxTtlMs must be a number greater than 0.",
|
|
61
|
+
});
|
|
62
|
+
}
|
|
43
63
|
const isPlausibleHash =
|
|
44
64
|
args.tokenHash.length >= MIN_HASH_LENGTH &&
|
|
45
65
|
HASH_PATTERN.test(args.tokenHash);
|
|
@@ -51,6 +71,18 @@ export const mint = mutation({
|
|
|
51
71
|
"Use client.hashToken() to produce a valid hash.",
|
|
52
72
|
});
|
|
53
73
|
}
|
|
74
|
+
const existing = await ctx.db
|
|
75
|
+
.query("tokens")
|
|
76
|
+
.withIndex("by_hash", (q) => q.eq("tokenHash", args.tokenHash))
|
|
77
|
+
.first();
|
|
78
|
+
if (existing !== null) {
|
|
79
|
+
// Lookups use `.unique()`; a second row with the same hash would make
|
|
80
|
+
// `validate` and `revoke` throw for that token.
|
|
81
|
+
throw new ConvexError({
|
|
82
|
+
code: "DUPLICATE_TOKEN_HASH",
|
|
83
|
+
message: "A token with this hash already exists.",
|
|
84
|
+
});
|
|
85
|
+
}
|
|
54
86
|
const ttl = clampTtl(args.ttlMs, MIN_TTL_MS, args.maxTtlMs, args.defaultTtlMs);
|
|
55
87
|
const now = Date.now();
|
|
56
88
|
return await ctx.db.insert("tokens", {
|
|
@@ -103,6 +135,12 @@ export const prune = mutation({
|
|
|
103
135
|
args: { before: v.number() },
|
|
104
136
|
returns: v.number(),
|
|
105
137
|
handler: async (ctx, args) => {
|
|
138
|
+
if (Number.isNaN(args.before)) {
|
|
139
|
+
throw new ConvexError({
|
|
140
|
+
code: "INVALID_BEFORE",
|
|
141
|
+
message: "before must be a number.",
|
|
142
|
+
});
|
|
143
|
+
}
|
|
106
144
|
const expired = await ctx.db
|
|
107
145
|
.query("tokens")
|
|
108
146
|
.withIndex("by_expires", (q) => q.lt("expiresAt", args.before))
|
package/src/component/queries.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { v } from "convex/values";
|
|
2
|
-
import { query } from "./_generated/server";
|
|
3
|
-
import { tokenMetadata, validateResult } from "./validators";
|
|
1
|
+
import { ConvexError, v } from "convex/values";
|
|
2
|
+
import { query } from "./_generated/server.js";
|
|
3
|
+
import { tokenMetadata, validateResult } from "./validators.js";
|
|
4
4
|
import { LIST_LIMIT_MAX } from "../shared.js";
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -46,7 +46,14 @@ export const list = query({
|
|
|
46
46
|
},
|
|
47
47
|
returns: v.array(tokenMetadata),
|
|
48
48
|
handler: async (ctx, args) => {
|
|
49
|
-
const
|
|
49
|
+
const requested = args.limit ?? 100;
|
|
50
|
+
if (!Number.isInteger(requested) || requested < 0) {
|
|
51
|
+
throw new ConvexError({
|
|
52
|
+
code: "INVALID_LIMIT",
|
|
53
|
+
message: "limit must be a non-negative integer.",
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
const limit = Math.min(requested, LIST_LIMIT_MAX);
|
|
50
57
|
const rows = await ctx.db
|
|
51
58
|
.query("tokens")
|
|
52
59
|
.withIndex("by_scope_resource", (q) =>
|
package/src/shared.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
/** Shared constants + pure utilities used by both `client/` and `component/`. */
|
|
2
2
|
|
|
3
|
+
import { ConvexError } from "convex/values";
|
|
4
|
+
|
|
3
5
|
export const COMPONENT_NAME = "tokens";
|
|
4
6
|
|
|
5
7
|
/** Default namespace when the host does not scope a token. */
|
|
@@ -65,8 +67,16 @@ export async function hashToken(
|
|
|
65
67
|
*
|
|
66
68
|
* @param bytes - Entropy in bytes. Default {@link DEFAULT_TOKEN_BYTES}.
|
|
67
69
|
* @returns The hex-encoded random token.
|
|
70
|
+
* @throws ConvexError `INVALID_TOKEN_BYTES` when `bytes` is not an integer >= 1.
|
|
68
71
|
*/
|
|
69
72
|
export function generateToken(bytes = DEFAULT_TOKEN_BYTES): string {
|
|
73
|
+
// `new Uint8Array(NaN)` and `(0)` are empty: that would mint the empty token.
|
|
74
|
+
if (!Number.isInteger(bytes) || bytes < 1) {
|
|
75
|
+
throw new ConvexError({
|
|
76
|
+
code: "INVALID_TOKEN_BYTES",
|
|
77
|
+
message: "tokenBytes must be an integer >= 1.",
|
|
78
|
+
});
|
|
79
|
+
}
|
|
70
80
|
const buf = new Uint8Array(bytes);
|
|
71
81
|
crypto.getRandomValues(buf);
|
|
72
82
|
return Array.from(buf)
|
package/src/test.ts
CHANGED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
import { convexTest } from "convex-test";
|
|
2
|
-
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
|
3
|
-
import { api, internal } from "./_generated/api";
|
|
4
|
-
import schema from "./schema";
|
|
5
|
-
|
|
6
|
-
const modules = import.meta.glob("./**/*.ts");
|
|
7
|
-
const HASH = "a".repeat(64);
|
|
8
|
-
const LONG_TTL = 2_592_000_000;
|
|
9
|
-
|
|
10
|
-
function setup() {
|
|
11
|
-
return convexTest(schema, modules);
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
async function mint(
|
|
15
|
-
t: ReturnType<typeof setup>,
|
|
16
|
-
tokenHash: string,
|
|
17
|
-
ttlMs = 86_400_000,
|
|
18
|
-
) {
|
|
19
|
-
return await t.mutation(api.mutations.mint, {
|
|
20
|
-
tokenHash,
|
|
21
|
-
scope: "global",
|
|
22
|
-
ttlMs,
|
|
23
|
-
defaultTtlMs: 86_400_000,
|
|
24
|
-
maxTtlMs: LONG_TTL,
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
describe("tokens component — cron sweep", () => {
|
|
29
|
-
beforeEach(() => {
|
|
30
|
-
vi.useFakeTimers();
|
|
31
|
-
vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
afterEach(() => {
|
|
35
|
-
vi.useRealTimers();
|
|
36
|
-
});
|
|
37
|
-
|
|
38
|
-
test("deletes expired tokens", async () => {
|
|
39
|
-
const t = setup();
|
|
40
|
-
const id = await mint(t, HASH);
|
|
41
|
-
vi.setSystemTime(Date.now() + 365 * 86_400_000);
|
|
42
|
-
await t.mutation(internal.mutations.pruneExpired, {});
|
|
43
|
-
await t.finishAllScheduledFunctions(vi.runAllTimers);
|
|
44
|
-
expect(await t.query(api.queries.getMetadata, { id })).toBeNull();
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
test("drops stale revoked tokens but keeps fresh revoked tokens", async () => {
|
|
48
|
-
const t = setup();
|
|
49
|
-
const freshHash = `b${"a".repeat(63)}`;
|
|
50
|
-
const staleId = await mint(t, HASH, LONG_TTL);
|
|
51
|
-
await t.mutation(api.mutations.revoke, { tokenHash: HASH, scope: "global" });
|
|
52
|
-
vi.setSystemTime(Date.now() + 86_400_000 + 1);
|
|
53
|
-
const freshId = await mint(t, freshHash, LONG_TTL);
|
|
54
|
-
await t.mutation(api.mutations.revoke, {
|
|
55
|
-
tokenHash: freshHash,
|
|
56
|
-
scope: "global",
|
|
57
|
-
});
|
|
58
|
-
await t.mutation(internal.mutations.pruneExpired, {});
|
|
59
|
-
expect(await t.query(api.queries.getMetadata, { id: staleId })).toBeNull();
|
|
60
|
-
expect(await t.query(api.queries.getMetadata, { id: freshId })).not.toBeNull();
|
|
61
|
-
});
|
|
62
|
-
|
|
63
|
-
test("self-reschedules until a backlog is drained", async () => {
|
|
64
|
-
const t = setup();
|
|
65
|
-
for (let i = 0; i < 257; i++) {
|
|
66
|
-
await mint(t, i.toString(16).padStart(64, "0"));
|
|
67
|
-
}
|
|
68
|
-
vi.setSystemTime(Date.now() + 365 * 86_400_000);
|
|
69
|
-
await t.mutation(internal.mutations.pruneExpired, {});
|
|
70
|
-
await t.finishAllScheduledFunctions(vi.runAllTimers);
|
|
71
|
-
expect(
|
|
72
|
-
await t.query(api.queries.list, { scope: "global", limit: 1000 }),
|
|
73
|
-
).toHaveLength(0);
|
|
74
|
-
});
|
|
75
|
-
});
|
package/src/react/index.test.tsx
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
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
|
-
});
|
package/src/unit.test.ts
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
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
|
-
});
|