@cardonjs/access-tokens 0.0.0-stage → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +457 -2
- package/dist/duration.d.ts +11 -0
- package/dist/duration.d.ts.map +1 -0
- package/dist/duration.js +21 -0
- package/dist/duration.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware.d.ts +53 -0
- package/dist/middleware.d.ts.map +1 -0
- package/dist/middleware.js +155 -0
- package/dist/middleware.js.map +1 -0
- package/dist/security-scheme.d.ts +12 -0
- package/dist/security-scheme.d.ts.map +1 -0
- package/dist/security-scheme.js +42 -0
- package/dist/security-scheme.js.map +1 -0
- package/dist/store.d.ts +58 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +2 -0
- package/dist/store.js.map +1 -0
- package/dist/testing.d.ts +7 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +66 -0
- package/dist/testing.js.map +1 -0
- package/dist/tokens.d.ts +74 -0
- package/dist/tokens.d.ts.map +1 -0
- package/dist/tokens.js +146 -0
- package/dist/tokens.js.map +1 -0
- package/dist/validation.d.ts +36 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +122 -0
- package/dist/validation.js.map +1 -0
- package/llms.txt +139 -0
- package/package.json +52 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Matias Terradas
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,458 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cardonjs/access-tokens
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Tokens that let someone act on one resource without an account: a guest checks the status of
|
|
4
|
+
the order they placed, a customer opens an invoice, a recipient accepts an invitation, someone
|
|
5
|
+
with a share link reads a document. Each token is unguessable, tied to one resource and a few
|
|
6
|
+
scopes, always expires and can be revoked.
|
|
7
|
+
|
|
8
|
+
- `accessTokens({ store, prefix, defaultTtl, maxTtl })`: `issue`, `verify`, `revoke`,
|
|
9
|
+
`revokeForResource` and `purgeExpired`.
|
|
10
|
+
- `requireAccessToken(tokens, { resource, scope })`: a Hono middleware that authorises a route
|
|
11
|
+
with a token read from a header, never from the URL.
|
|
12
|
+
- `accessTokenSecurityScheme(header?)`: the OpenAPI security scheme, registered by the
|
|
13
|
+
middleware on its own.
|
|
14
|
+
- `AccessTokenStore`: the store interface. `@cardonjs/db-d1/access-tokens` is the D1 store;
|
|
15
|
+
`@cardonjs/access-tokens/testing` has `memoryAccessTokenStore` for tests; every store passes
|
|
16
|
+
`accessTokenStoreContract` from `@cardonjs/testing`.
|
|
17
|
+
|
|
18
|
+
The package knows nothing about orders: the resource types, the scopes, how long a token lives,
|
|
19
|
+
when it is issued and what the routes do all stay in the project.
|
|
20
|
+
|
|
21
|
+
Peer dependencies: `@cardonjs/core`, `hono`. Standard web APIs only (`crypto.getRandomValues`,
|
|
22
|
+
`crypto.subtle`), so it runs on Workers, Node, Bun and Deno.
|
|
23
|
+
|
|
24
|
+
For coding agents: `llms.txt`, shipped next to this README in the package, is a compact usage guide (public API, a minimal example, common mistakes).
|
|
25
|
+
|
|
26
|
+
## Example
|
|
27
|
+
|
|
28
|
+
A guest places an order and gets a token to check it later. The route is public for the
|
|
29
|
+
app's guard (no login), and the token authorises it. The routes that take a token also get a
|
|
30
|
+
rate limit per IP.
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { requireAuth } from "@cardonjs/auth";
|
|
34
|
+
import { accessTokens, requireAccessToken } from "@cardonjs/access-tokens";
|
|
35
|
+
import {
|
|
36
|
+
type CardonEnv,
|
|
37
|
+
createApp,
|
|
38
|
+
created,
|
|
39
|
+
defineModule,
|
|
40
|
+
errorEnvelopeSchema,
|
|
41
|
+
NotFoundError,
|
|
42
|
+
ok,
|
|
43
|
+
rateLimit,
|
|
44
|
+
rateLimitKeys,
|
|
45
|
+
successEnvelope,
|
|
46
|
+
UnauthorizedError,
|
|
47
|
+
workersRateLimiter,
|
|
48
|
+
} from "@cardonjs/core";
|
|
49
|
+
import { d1Database } from "@cardonjs/db-d1";
|
|
50
|
+
import { d1AccessTokenStore } from "@cardonjs/db-d1/access-tokens";
|
|
51
|
+
import { createRoute, z } from "@hono/zod-openapi";
|
|
52
|
+
|
|
53
|
+
type Bindings = { DB: D1Database; TOKEN_LIMITER: RateLimit };
|
|
54
|
+
const adapters = (env: Bindings) => {
|
|
55
|
+
const db = d1Database(env.DB, { schema });
|
|
56
|
+
return {
|
|
57
|
+
auth: sessionAuth(env), // your Authenticator
|
|
58
|
+
orders: ordersRepository(db), // your repository
|
|
59
|
+
limiter: workersRateLimiter(env.TOKEN_LIMITER, { periodSeconds: 60 }),
|
|
60
|
+
tokens: accessTokens({
|
|
61
|
+
store: d1AccessTokenStore(db.client),
|
|
62
|
+
prefix: "ord",
|
|
63
|
+
defaultTtl: "7d",
|
|
64
|
+
maxTtl: "30d",
|
|
65
|
+
}),
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
type AppEnv = CardonEnv<Bindings, ReturnType<typeof adapters>>;
|
|
69
|
+
|
|
70
|
+
const order = z.object({ id: z.string(), status: z.string() });
|
|
71
|
+
const errors = (description: string) => ({
|
|
72
|
+
description,
|
|
73
|
+
content: { "application/json": { schema: errorEnvelopeSchema } },
|
|
74
|
+
});
|
|
75
|
+
const perIp = rateLimit<AppEnv>({
|
|
76
|
+
limiter: (c) => c.var.adapters.limiter,
|
|
77
|
+
key: rateLimitKeys.ip,
|
|
78
|
+
name: "access-tokens",
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
const placeOrder = createRoute({
|
|
82
|
+
method: "post",
|
|
83
|
+
path: "/",
|
|
84
|
+
tags: ["Orders"],
|
|
85
|
+
summary: "Place an order as a guest",
|
|
86
|
+
middleware: perIp,
|
|
87
|
+
request: {
|
|
88
|
+
body: { required: true, content: { "application/json": { schema: z.object({ sku: z.string() }) } } },
|
|
89
|
+
},
|
|
90
|
+
responses: {
|
|
91
|
+
201: {
|
|
92
|
+
description: "Placed; `token` is shown once",
|
|
93
|
+
content: {
|
|
94
|
+
"application/json": { schema: successEnvelope(z.object({ order, token: z.string() })) },
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const getOrder = createRoute({
|
|
101
|
+
method: "get",
|
|
102
|
+
path: "/{id}",
|
|
103
|
+
tags: ["Orders"],
|
|
104
|
+
summary: "Get an order with its access token",
|
|
105
|
+
middleware: [
|
|
106
|
+
perIp,
|
|
107
|
+
requireAccessToken<AppEnv>((c) => c.var.adapters.tokens, {
|
|
108
|
+
resource: { type: "order", param: "id" }, // the `id` path parameter
|
|
109
|
+
scope: "order:read",
|
|
110
|
+
}),
|
|
111
|
+
] as const,
|
|
112
|
+
request: { params: z.object({ id: z.string() }) },
|
|
113
|
+
responses: {
|
|
114
|
+
200: { description: "The order", content: { "application/json": { schema: successEnvelope(order) } } },
|
|
115
|
+
401: errors("No valid token for this order"),
|
|
116
|
+
404: errors("Not found"),
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
const ordersModule = defineModule<AppEnv>({
|
|
121
|
+
name: "orders",
|
|
122
|
+
prefix: "/v1/orders",
|
|
123
|
+
routes: (app) => {
|
|
124
|
+
app.openapi(placeOrder, async (c) => {
|
|
125
|
+
const placed = await c.var.adapters.orders.create(c.req.valid("json"));
|
|
126
|
+
const { token } = await c.var.adapters.tokens.issue({
|
|
127
|
+
resource: { type: "order", id: placed.id },
|
|
128
|
+
scopes: ["order:read", "order:cancel"],
|
|
129
|
+
});
|
|
130
|
+
return created(c, { order: placed, token });
|
|
131
|
+
});
|
|
132
|
+
app.openapi(getOrder, async (c) => {
|
|
133
|
+
const grant = c.var.accessToken; // what the token grants: resource, scopes, expiresAt
|
|
134
|
+
if (grant === undefined) throw new UnauthorizedError(); // fail closed
|
|
135
|
+
const found = await c.var.adapters.orders.get(grant.resourceId);
|
|
136
|
+
if (!found) throw new NotFoundError();
|
|
137
|
+
return ok(c, found);
|
|
138
|
+
});
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
export default createApp(adapters, {
|
|
143
|
+
guard: requireAuth<AppEnv>({
|
|
144
|
+
authenticator: (c) => c.var.adapters.auth,
|
|
145
|
+
public: ["POST /v1/orders", "GET /v1/orders/:id"], // the token authorises GET /v1/orders/:id
|
|
146
|
+
}),
|
|
147
|
+
}).register(ordersModule);
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
The client sends the token in the `Authorization` header:
|
|
151
|
+
|
|
152
|
+
```http
|
|
153
|
+
GET /v1/orders/019a8a3c-5b2e-7c41-9d3f-2a6b8e4f1c07
|
|
154
|
+
Authorization: Bearer <the token: ord_ and 43 characters>
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## Tokens
|
|
158
|
+
|
|
159
|
+
- **Format.** `<prefix>_<43 base64url characters>`: 32 random bytes from
|
|
160
|
+
`crypto.getRandomValues` (256 bits). The prefix is the project's: lowercase letters and digits,
|
|
161
|
+
2 to 12 characters, default `cat`. A recognisable prefix lets secret scanners and log filters
|
|
162
|
+
spot a leaked token; add a rule for yours (this repository's `.gitleaks.toml` has one for
|
|
163
|
+
`cat_`).
|
|
164
|
+
- **Stored as a hash.** Only the SHA-256 of the token is stored (with 256 bits of entropy a plain
|
|
165
|
+
hash is enough and keeps lookups fast). `issue` returns the token once: hand it to its holder
|
|
166
|
+
and never log or store it. `verify` compares the stored hash in constant time.
|
|
167
|
+
- **Expiry is mandatory.** `issue({ ttl })` takes at most `maxTtl` (default `"30d"`, at most
|
|
168
|
+
`"366d"`); without `ttl` it uses `defaultTtl` (default `"1d"`). A duration is a whole number of
|
|
169
|
+
seconds or a string such as `"15m"`, `"12h"` or `"7d"`. There is no token that never expires.
|
|
170
|
+
- **Record and grant.** The store keeps `{ id, tokenHash, resourceType, resourceId, scopes,
|
|
171
|
+
createdAt, expiresAt, revokedAt? }` (`AccessTokenRecord`), with `id` from core's `newId`. No
|
|
172
|
+
personal data. `issue`, `verify` and `c.var.accessToken` hand out the same fields without
|
|
173
|
+
`tokenHash` (`AccessTokenGrant`): only stores see the hash.
|
|
174
|
+
- **Input rules.** A resource type is 1 to 64 lowercase letters, digits, `_`, `.` or `-`,
|
|
175
|
+
starting with a letter (`order`, `share-link`); a resource id is 1 to 255 printable ASCII
|
|
176
|
+
characters without spaces; a token has 1 to 32 scopes, each 1 to 64 lowercase letters, digits,
|
|
177
|
+
`:`, `_`, `.` or `-` (`order:read`). Anything else throws a `TypeError`.
|
|
178
|
+
|
|
179
|
+
## The middleware
|
|
180
|
+
|
|
181
|
+
`requireAccessToken(tokens, options)` takes the `AccessTokens` instance or a function of the
|
|
182
|
+
context (`(c) => c.var.adapters.tokens`, since the store depends on the env).
|
|
183
|
+
|
|
184
|
+
- **`resource`**: `{ type, param }` reads the id from a path parameter; a function
|
|
185
|
+
`(c) => ({ type, id })` (it may be async) computes it. The token must be for exactly this
|
|
186
|
+
resource.
|
|
187
|
+
- **`scope`**: one scope or a list; the token needs all of them.
|
|
188
|
+
- **`header`**: default `Authorization`, as `Bearer <token>`. Any other header (`X-Order-Token`)
|
|
189
|
+
carries the bare token. The token is never read from the query string, the path or a cookie:
|
|
190
|
+
URLs end up in logs, browser history and `Referer` headers.
|
|
191
|
+
- **One answer for every failure.** No token, a malformed, unknown, expired or revoked one, a
|
|
192
|
+
token for another resource or without the scope: all get the same `401 UNAUTHORIZED` envelope
|
|
193
|
+
(message "A valid access token is required.") with `WWW-Authenticate: Bearer` (or
|
|
194
|
+
`AccessToken header="X-Order-Token"` for a custom header). A client cannot tell a valid token
|
|
195
|
+
for another resource from a made-up one. The reason is logged at `info` (with the record id
|
|
196
|
+
when there is one), never the token or its hash.
|
|
197
|
+
- **A store failure** answers `503` and logs the error's name only.
|
|
198
|
+
- **`c.var.accessToken`** is the verified grant (`AccessTokenGrant`: the record without its
|
|
199
|
+
hash).
|
|
200
|
+
- **Documented automatically.** The route gets the `accessToken` security scheme (HTTP bearer, or
|
|
201
|
+
an API key in the custom header) and the `401` and `503` responses in the OpenAPI document.
|
|
202
|
+
|
|
203
|
+
List the route as public in `requireAuth`: the guard then does not ask for a login, and the
|
|
204
|
+
middleware is the route's authorisation. On a route that is not public, both a login and a
|
|
205
|
+
token are needed.
|
|
206
|
+
|
|
207
|
+
> **Warning: a route listed in `requireAuth({ public })` without `requireAccessToken` is fully
|
|
208
|
+
> open.** Forgetting the middleware, or putting it in the wrong `createRoute` object, leaves the
|
|
209
|
+
> route with no authorisation at all, and nothing fails at startup. For every token route:
|
|
210
|
+
>
|
|
211
|
+
> - add a route test that expects `401` with no `Authorization` header (and with a token for
|
|
212
|
+
> another resource);
|
|
213
|
+
> - read `c.var.accessToken` in the handler and fail closed when it is `undefined` on a route
|
|
214
|
+
> that is not `optional` (`if (grant === undefined) throw new UnauthorizedError()`, as in the
|
|
215
|
+
> example), and take the resource id from the grant or check it against the path.
|
|
216
|
+
|
|
217
|
+
### Routes for a token or a signed-in user
|
|
218
|
+
|
|
219
|
+
With `optional: true` a request without a token passes with `c.var.accessToken` undefined, so
|
|
220
|
+
the handler can serve another kind of caller; a token that is sent must still be valid.
|
|
221
|
+
|
|
222
|
+
What counts as "no token" is decided from the raw header value:
|
|
223
|
+
|
|
224
|
+
- **`Authorization`**: a value that does not contain `<prefix>_` anywhere (`Basic …`, a session
|
|
225
|
+
bearer such as a JWT) is another credential and passes as no token. A value that contains it
|
|
226
|
+
must be exactly `Bearer <one valid token>` (the scheme in any case, separated by spaces), or the
|
|
227
|
+
request gets the same `401`: a tab, a no-break space, comma-joined duplicate headers
|
|
228
|
+
(`Bearer ord_…, Bearer x`) or another scheme (`Token ord_…`) are rejected, never served
|
|
229
|
+
anonymously. A credential of another kind that happens to contain `<prefix>_` is rejected too;
|
|
230
|
+
a longer prefix makes that rarer.
|
|
231
|
+
- **A custom header** is only for these tokens: an absent or empty header is no token, any other
|
|
232
|
+
value must be exactly one valid token (only spaces and tabs around it are ignored).
|
|
233
|
+
|
|
234
|
+
List the route in `requireAuth({ optional })` (`@cardonjs/auth`): the guard then authenticates
|
|
235
|
+
a caller who presents a credential, lets one without a credential through with no identity, and
|
|
236
|
+
answers `401` to a credential that is presented but invalid. The handler serves the token
|
|
237
|
+
holder first and requires a signed-in user otherwise:
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
import { getIdentity, requireAuth } from "@cardonjs/auth";
|
|
241
|
+
|
|
242
|
+
const getSharedOrder = createRoute({
|
|
243
|
+
method: "get",
|
|
244
|
+
path: "/{id}",
|
|
245
|
+
tags: ["Orders"],
|
|
246
|
+
summary: "Get an order with its access token or as its signed-in customer",
|
|
247
|
+
middleware: requireAccessToken<AppEnv>((c) => c.var.adapters.tokens, {
|
|
248
|
+
resource: { type: "order", param: "id" },
|
|
249
|
+
scope: "order:read",
|
|
250
|
+
optional: true,
|
|
251
|
+
}),
|
|
252
|
+
// The session, the token, or neither (the handler then answers 401).
|
|
253
|
+
security: [{ usersSession: [] }, { accessToken: [] }, {}],
|
|
254
|
+
request: { params: z.object({ id: z.string() }) },
|
|
255
|
+
responses: {
|
|
256
|
+
200: {
|
|
257
|
+
description: "The order",
|
|
258
|
+
content: { "application/json": { schema: successEnvelope(order) } },
|
|
259
|
+
},
|
|
260
|
+
401: errors("Neither a valid token for this order nor a session"),
|
|
261
|
+
404: errors("Not found"),
|
|
262
|
+
},
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
app.openapi(getSharedOrder, async (c) => {
|
|
266
|
+
const { id } = c.req.valid("param");
|
|
267
|
+
const grant = c.var.accessToken;
|
|
268
|
+
if (grant !== undefined) {
|
|
269
|
+
// The middleware checked that the token is for this order and has `order:read`.
|
|
270
|
+
const found = await c.var.adapters.orders.get(grant.resourceId);
|
|
271
|
+
if (!found) throw new NotFoundError();
|
|
272
|
+
return ok(c, found);
|
|
273
|
+
}
|
|
274
|
+
// No token: the guard authenticated the session, if there was one. Fail closed without it.
|
|
275
|
+
const user = getIdentity(c); // 401 when there is no identity
|
|
276
|
+
const found = await c.var.adapters.orders.get(id);
|
|
277
|
+
// Authorise too: a signed-in user is not necessarily this order's customer.
|
|
278
|
+
if (!found || found.customerId !== user.id) throw new NotFoundError();
|
|
279
|
+
return ok(c, found);
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
const guard = requireAuth<AppEnv>({
|
|
283
|
+
authenticator: (c) => c.var.adapters.auth, // reads a session cookie, not `Authorization`
|
|
284
|
+
public: ["POST /v1/orders"],
|
|
285
|
+
optional: ["GET /v1/orders/:id"], // the token holder or the signed-in customer
|
|
286
|
+
});
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
> **Warning: the guard runs before `requireAccessToken`, so the two must read different
|
|
290
|
+
> headers.** On an optional route a credential the authenticator rejects is a `401`, never
|
|
291
|
+
> downgraded to anonymous. An authenticator that reads `Authorization: Bearer` (a JWT or an API
|
|
292
|
+
> key) sees the access token there as an invalid credential of its own and answers `401` before
|
|
293
|
+
> the token is checked. With such an authenticator, take the token in a custom header
|
|
294
|
+
> (`requireAccessToken(..., { header: "X-Order-Token", optional: true })`). An authenticator
|
|
295
|
+
> that reads a cookie (such as `@cardonjs/users`) or its own header leaves `Authorization` to the
|
|
296
|
+
> token. And:
|
|
297
|
+
>
|
|
298
|
+
> - **list the route in `optional`, not `public`**: on a public route no authentication is
|
|
299
|
+
> attempted, so `getIdentity(c)` answers `401` to every signed-in user (safe, but the session
|
|
300
|
+
> never works);
|
|
301
|
+
> - **fail closed when there is no grant**: with neither a token nor a session both
|
|
302
|
+
> `c.var.accessToken` and the identity are `undefined`; `getIdentity(c)` throws `401` (with
|
|
303
|
+
> `getOptionalIdentity(c)`, check for `undefined` yourself);
|
|
304
|
+
> - test the route with no credential (`401`), a token for another resource (`401`), a session
|
|
305
|
+
> for another customer (`404`), and both kinds of valid caller.
|
|
306
|
+
|
|
307
|
+
`requireAccessToken` with `optional: true` adds no `security` of its own (the guard's status
|
|
308
|
+
decides it); declare `security` on the `createRoute`, as above, to list the token and the
|
|
309
|
+
session as alternatives.
|
|
310
|
+
|
|
311
|
+
## Links: keep the token in the URL fragment
|
|
312
|
+
|
|
313
|
+
Links in an email, a QR code or a confirmation page cannot set a header. Put the token in the
|
|
314
|
+
**fragment** of a link to the web app, never in the query string:
|
|
315
|
+
|
|
316
|
+
```
|
|
317
|
+
https://app.example/orders/019a8a3c-5b2e-7c41-9d3f-2a6b8e4f1c07#token=<the token>
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
Browsers never send the fragment to a server, so it stays out of server logs, CDN logs and
|
|
321
|
+
`Referer` headers. The web app reads it, removes it from the address bar and sends it in the
|
|
322
|
+
header:
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
const token = new URLSearchParams(location.hash.slice(1)).get("token");
|
|
326
|
+
history.replaceState(null, "", location.pathname + location.search); // drop the fragment
|
|
327
|
+
const res = await fetch(`${api}/v1/orders/${orderId}`, {
|
|
328
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
329
|
+
});
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
The fragment keeps the token out of servers, not out of everything else:
|
|
333
|
+
|
|
334
|
+
- **Disable click tracking** in the email provider for messages that carry these links. Click
|
|
335
|
+
trackers rewrite the link through their own server and embed the full URL, fragment included.
|
|
336
|
+
- **Drop the fragment first.** Run `history.replaceState` (as above) before any analytics or
|
|
337
|
+
third-party script can read `location`, ideally in an inline script at the top of the page;
|
|
338
|
+
better still, keep third-party scripts off the page.
|
|
339
|
+
- **The token stays where the link was sent**: in the email or chat history, and in the
|
|
340
|
+
link-preview caches of chat apps and mail clients. Prefer short TTLs and revoke the token
|
|
341
|
+
(`revoke` or `revokeForResource`) once its job is done.
|
|
342
|
+
- **Serve the page with `Referrer-Policy: no-referrer`.** Browsers never put the fragment in a
|
|
343
|
+
`Referer`, but they do send the path, which holds the resource id; `no-referrer` keeps the
|
|
344
|
+
path from reaching any other site the page links to or loads from. Core's secure headers
|
|
345
|
+
already set a strict policy for the API itself.
|
|
346
|
+
|
|
347
|
+
## Live updates (WebSockets)
|
|
348
|
+
|
|
349
|
+
A browser cannot send the token on a WebSocket upgrade, and the token never goes in the socket's
|
|
350
|
+
URL. To let a token holder follow its resource live, exchange the token for a one-time ticket of
|
|
351
|
+
`@cardonjs/realtime-do`: a route with `requireAccessToken` calls `issueRoomTicket` (identity
|
|
352
|
+
`{ id: grant.id, kind: "guest" }`, `connectionExpiresAt: grant.expiresAt`), and the client offers
|
|
353
|
+
the ticket with the upgrade. See "Clients without a cookie: tickets" in the `@cardonjs/realtime-do`
|
|
354
|
+
README. Revoking a token does not close a socket that is already open: call that package's
|
|
355
|
+
`disconnect` too.
|
|
356
|
+
|
|
357
|
+
## Rate limiting
|
|
358
|
+
|
|
359
|
+
A token cannot be guessed, but every request with one costs a store lookup. Put a rate limit per
|
|
360
|
+
IP on the routes that take tokens (`rateLimit` with `rateLimitKeys.ip`, as in the example) and on
|
|
361
|
+
the routes that issue them, so one client can neither hammer the store nor fill it.
|
|
362
|
+
|
|
363
|
+
## Revoking and purging
|
|
364
|
+
|
|
365
|
+
```ts
|
|
366
|
+
await tokens.revoke(record.id); // one token
|
|
367
|
+
await tokens.revokeForResource({ type: "order", id }); // every token of the order, e.g. once it is delivered
|
|
368
|
+
await tokens.purgeExpired({ olderThan: "7d" }); // delete records expired more than 7 days ago
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
`revoke` resolves whether the token was revoked now; `revokeForResource` and `purgeExpired`
|
|
372
|
+
resolve how many records they changed. Run `purgeExpired` from an hourly Cron Trigger (e.g.
|
|
373
|
+
with `createScheduled` from `@cardonjs/jobs`); keeping recently expired records for a while only
|
|
374
|
+
makes the logged reason `expired` instead of `invalid`, the answer is the same `401`.
|
|
375
|
+
|
|
376
|
+
## API
|
|
377
|
+
|
|
378
|
+
```ts
|
|
379
|
+
type Duration = number | `${number}${"s" | "m" | "h" | "d"}`; // seconds, or "15m", "12h", "7d"
|
|
380
|
+
|
|
381
|
+
function accessTokens(options: {
|
|
382
|
+
store: AccessTokenStore;
|
|
383
|
+
prefix?: string; // default "cat"
|
|
384
|
+
defaultTtl?: Duration; // default "1d" (or maxTtl when shorter)
|
|
385
|
+
maxTtl?: Duration; // default "30d", at most "366d"
|
|
386
|
+
now?: () => Date;
|
|
387
|
+
}): AccessTokens;
|
|
388
|
+
|
|
389
|
+
interface AccessTokens {
|
|
390
|
+
readonly prefix: string;
|
|
391
|
+
issue(input: {
|
|
392
|
+
resource: { type: string; id: string };
|
|
393
|
+
scopes: readonly string[];
|
|
394
|
+
ttl?: Duration;
|
|
395
|
+
}): Promise<{ token: string; record: AccessTokenGrant }>;
|
|
396
|
+
verify(token: unknown): Promise<
|
|
397
|
+
| { ok: true; record: AccessTokenGrant }
|
|
398
|
+
| { ok: false; reason: "missing" | "invalid" | "expired" | "revoked" }
|
|
399
|
+
>;
|
|
400
|
+
revoke(id: string): Promise<boolean>;
|
|
401
|
+
revokeForResource(resource: { type: string; id: string }): Promise<number>;
|
|
402
|
+
purgeExpired(options?: { olderThan?: Duration }): Promise<number>;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function requireAccessToken<E extends Env>(
|
|
406
|
+
tokens: AccessTokens | ((c: Context<E>) => AccessTokens),
|
|
407
|
+
options: {
|
|
408
|
+
resource: { type: string; param: string } | ((c: Context<E>) => AccessTokenResource | Promise<AccessTokenResource>);
|
|
409
|
+
scope: string | readonly [string, ...string[]];
|
|
410
|
+
header?: string; // default "Authorization" (Bearer)
|
|
411
|
+
optional?: boolean; // default false
|
|
412
|
+
},
|
|
413
|
+
): MiddlewareHandler<E & { Variables: { accessToken: AccessTokenGrant | undefined } }>;
|
|
414
|
+
|
|
415
|
+
function accessTokenSecurityScheme(header?: string): SecuritySchemeObject;
|
|
416
|
+
const ACCESS_TOKEN_SECURITY_SCHEME: "accessToken";
|
|
417
|
+
function hashAccessToken(token: string): Promise<string>; // lowercase hex SHA-256
|
|
418
|
+
|
|
419
|
+
// What callers see; the store keeps `AccessTokenRecord = AccessTokenGrant & { tokenHash }`.
|
|
420
|
+
interface AccessTokenGrant {
|
|
421
|
+
id: string;
|
|
422
|
+
resourceType: string;
|
|
423
|
+
resourceId: string;
|
|
424
|
+
scopes: readonly string[];
|
|
425
|
+
createdAt: Date;
|
|
426
|
+
expiresAt: Date;
|
|
427
|
+
revokedAt?: Date;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
interface AccessTokenStore {
|
|
431
|
+
insert(record: AccessTokenRecord): Promise<void>; // rejects on a duplicate id or hash
|
|
432
|
+
findByHash(tokenHash: string): Promise<AccessTokenRecord | undefined>;
|
|
433
|
+
revoke(id: string, at: Date): Promise<boolean>;
|
|
434
|
+
revokeForResource(resourceType: string, resourceId: string, at: Date): Promise<number>;
|
|
435
|
+
purgeExpired(before: Date): Promise<number>; // expiresAt <= before
|
|
436
|
+
}
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
`verify` checks the format before it queries the store, and rejects (the middleware answers
|
|
440
|
+
`503`) when the store fails or returns a malformed record: never a pass.
|
|
441
|
+
|
|
442
|
+
## Testing
|
|
443
|
+
|
|
444
|
+
`memoryAccessTokenStore()` from `@cardonjs/access-tokens/testing` keeps records in memory (per
|
|
445
|
+
isolate; tests and local development only). A new store passes the shared contract:
|
|
446
|
+
|
|
447
|
+
```ts
|
|
448
|
+
import { accessTokenStoreContract } from "@cardonjs/testing";
|
|
449
|
+
|
|
450
|
+
it.each(accessTokenStoreContract.map((c) => [c.name, c] as const))("%s", (_, c) =>
|
|
451
|
+
c.run({ create: () => myStore() }),
|
|
452
|
+
);
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
## Out of scope
|
|
456
|
+
|
|
457
|
+
Tokens for whole accounts (`@cardonjs/users`), refresh tokens, JWT or other stateless tokens,
|
|
458
|
+
one-time tokens (a later `maxUses` option) and a record of who used a token.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A length of time: whole seconds as a number, or a string of a whole number and a unit,
|
|
3
|
+
* `s` (seconds), `m` (minutes), `h` (hours) or `d` (days), e.g. `"15m"` or `"7d"`.
|
|
4
|
+
*/
|
|
5
|
+
export type Duration = number | `${number}${"s" | "m" | "h" | "d"}`;
|
|
6
|
+
/**
|
|
7
|
+
* The seconds of a {@link Duration}, or `undefined` when it is not one: a number must be a
|
|
8
|
+
* positive safe integer; a string has no sign, spaces, decimals or leading zeros.
|
|
9
|
+
*/
|
|
10
|
+
export declare function durationSeconds(value: unknown): number | undefined;
|
|
11
|
+
//# sourceMappingURL=duration.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"duration.d.ts","sourceRoot":"","sources":["../src/duration.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,GAAG,MAAM,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,EAAE,CAAC;AAKpE;;;GAGG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAWlE"}
|
package/dist/duration.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const DURATION = /^([1-9][0-9]{0,8})([smhd])$/;
|
|
2
|
+
const UNIT_SECONDS = { s: 1, m: 60, h: 3_600, d: 86_400 };
|
|
3
|
+
/**
|
|
4
|
+
* The seconds of a {@link Duration}, or `undefined` when it is not one: a number must be a
|
|
5
|
+
* positive safe integer; a string has no sign, spaces, decimals or leading zeros.
|
|
6
|
+
*/
|
|
7
|
+
export function durationSeconds(value) {
|
|
8
|
+
if (typeof value === "number") {
|
|
9
|
+
return Number.isSafeInteger(value) && value > 0 ? value : undefined;
|
|
10
|
+
}
|
|
11
|
+
if (typeof value !== "string")
|
|
12
|
+
return undefined;
|
|
13
|
+
const match = DURATION.exec(value);
|
|
14
|
+
const amount = match?.[1];
|
|
15
|
+
const unit = match?.[2];
|
|
16
|
+
if (amount === undefined || unit === undefined)
|
|
17
|
+
return undefined;
|
|
18
|
+
const seconds = Number(amount) * (UNIT_SECONDS[unit] ?? 0);
|
|
19
|
+
return Number.isSafeInteger(seconds) && seconds > 0 ? seconds : undefined;
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=duration.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"duration.js","sourceRoot":"","sources":["../src/duration.ts"],"names":[],"mappings":"AAMA,MAAM,QAAQ,GAAG,6BAA6B,CAAC;AAC/C,MAAM,YAAY,GAAqC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC;AAE5F;;;GAGG;AACH,MAAM,UAAU,eAAe,CAAC,KAAc;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;IACtE,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAC;IAChD,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACnC,MAAM,MAAM,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;IAC1B,MAAM,IAAI,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;IACxB,IAAI,MAAM,KAAK,SAAS,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IACjE,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAC3D,OAAO,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC,IAAI,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAC5E,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type { Duration } from "./duration.js";
|
|
2
|
+
export { type AccessTokenResourceSelector, type AccessTokenVariables, type RequireAccessTokenOptions, requireAccessToken, } from "./middleware.js";
|
|
3
|
+
export { ACCESS_TOKEN_SECURITY_SCHEME, accessTokenSecurityScheme } from "./security-scheme.js";
|
|
4
|
+
export type { AccessTokenGrant, AccessTokenRecord, AccessTokenResource, AccessTokenStore, } from "./store.js";
|
|
5
|
+
export { type AccessTokenFailure, type AccessTokens, type AccessTokensOptions, type AccessTokenVerification, accessTokens, hashAccessToken, type IssueAccessTokenInput, type IssuedAccessToken, type PurgeExpiredOptions, } from "./tokens.js";
|
|
6
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,EACL,KAAK,2BAA2B,EAChC,KAAK,oBAAoB,EACzB,KAAK,yBAAyB,EAC9B,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,4BAA4B,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AAC/F,YAAY,EACV,gBAAgB,EAChB,iBAAiB,EACjB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,KAAK,kBAAkB,EACvB,KAAK,YAAY,EACjB,KAAK,mBAAmB,EACxB,KAAK,uBAAuB,EAC5B,YAAY,EACZ,eAAe,EACf,KAAK,qBAAqB,EAC1B,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,GACzB,MAAM,aAAa,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAIL,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,4BAA4B,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AAO/F,OAAO,EAKL,YAAY,EACZ,eAAe,GAIhB,MAAM,aAAa,CAAC"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Context, Env, MiddlewareHandler } from "hono";
|
|
2
|
+
import type { AccessTokenGrant, AccessTokenResource } from "./store.js";
|
|
3
|
+
import type { AccessTokens } from "./tokens.js";
|
|
4
|
+
/**
|
|
5
|
+
* `c.var.accessToken`: the verified grant (the record without its hash), or `undefined` on an
|
|
6
|
+
* `optional` route without a token.
|
|
7
|
+
*/
|
|
8
|
+
export interface AccessTokenVariables {
|
|
9
|
+
accessToken: AccessTokenGrant | undefined;
|
|
10
|
+
}
|
|
11
|
+
/** Which resource the route acts on: a path parameter, or computed from the request. */
|
|
12
|
+
export type AccessTokenResourceSelector<E extends Env> = {
|
|
13
|
+
readonly type: string;
|
|
14
|
+
readonly param: string;
|
|
15
|
+
} | ((c: Context<E>) => AccessTokenResource | Promise<AccessTokenResource>);
|
|
16
|
+
export interface RequireAccessTokenOptions<E extends Env> {
|
|
17
|
+
/**
|
|
18
|
+
* The resource the route acts on: `{ type: "order", param: "id" }` (the `id` path parameter)
|
|
19
|
+
* or a function of the context. The token must be for exactly this resource.
|
|
20
|
+
*/
|
|
21
|
+
readonly resource: AccessTokenResourceSelector<E>;
|
|
22
|
+
/** The scope the route needs, or several (all needed), e.g. `"order:read"`. */
|
|
23
|
+
readonly scope: string | readonly [string, ...string[]];
|
|
24
|
+
/**
|
|
25
|
+
* The header the token comes in. Default: `"Authorization"`, as `Bearer <token>`; any other
|
|
26
|
+
* header carries the bare token. Never a query string or path segment.
|
|
27
|
+
*/
|
|
28
|
+
readonly header?: string;
|
|
29
|
+
/**
|
|
30
|
+
* Let requests without a token through, with `c.var.accessToken` undefined, so the route can
|
|
31
|
+
* also serve another kind of caller, whom the handler must then authenticate itself. With the
|
|
32
|
+
* `Authorization` header, only a value without `<prefix>_` anywhere counts as no token (another
|
|
33
|
+
* scheme or credential); a value containing it must be exactly `Bearer <one valid token>`. A
|
|
34
|
+
* custom header with any value must hold exactly one valid token. Default: `false`.
|
|
35
|
+
*/
|
|
36
|
+
readonly optional?: boolean;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Authorises a route with an access token from `tokens` (an instance, or a function of the
|
|
40
|
+
* context such as `(c) => c.var.adapters.tokens`). The token is read only from one header
|
|
41
|
+
* (default `Authorization: Bearer <token>`), never from the query string or the path.
|
|
42
|
+
*
|
|
43
|
+
* Every failure (no token, a malformed, unknown, expired or revoked one, a token for another
|
|
44
|
+
* resource or without the scope) answers the same `401 UNAUTHORIZED` envelope with a
|
|
45
|
+
* `WWW-Authenticate` header; the reason is logged at `info`, the token never. A store failure
|
|
46
|
+
* answers `503`. On success `c.var.accessToken` is the grant (the record without its hash). List the route as public in
|
|
47
|
+
* `requireAuth`: this middleware is its authorisation. Throws a `TypeError` at creation for
|
|
48
|
+
* invalid options.
|
|
49
|
+
*/
|
|
50
|
+
export declare function requireAccessToken<E extends Env>(tokens: AccessTokens | ((c: Context<E>) => AccessTokens), options: RequireAccessTokenOptions<E>): MiddlewareHandler<E & {
|
|
51
|
+
Variables: AccessTokenVariables;
|
|
52
|
+
}>;
|
|
53
|
+
//# sourceMappingURL=middleware.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAO5D,OAAO,KAAK,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACxE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAGhD;;;GAGG;AACH,MAAM,WAAW,oBAAoB;IACnC,WAAW,EAAE,gBAAgB,GAAG,SAAS,CAAC;CAC3C;AAED,wFAAwF;AACxF,MAAM,MAAM,2BAA2B,CAAC,CAAC,SAAS,GAAG,IACjD;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GACjD,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC,CAAC;AAE5E,MAAM,WAAW,yBAAyB,CAAC,CAAC,SAAS,GAAG;IACtD;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAE,2BAA2B,CAAC,CAAC,CAAC,CAAC;IAClD,+EAA+E;IAC/E,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;IACxD;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB;;;;;;OAMG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B;AA8CD;;;;;;;;;;;GAWG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,GAAG,EAC9C,MAAM,EAAE,YAAY,GAAG,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,YAAY,CAAC,EACxD,OAAO,EAAE,yBAAyB,CAAC,CAAC,CAAC,GACpC,iBAAiB,CAAC,CAAC,GAAG;IAAE,SAAS,EAAE,oBAAoB,CAAA;CAAE,CAAC,CA+G5D"}
|