@cardonjs/access-tokens 0.0.0-stage → 0.1.3
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 +447 -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
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { AccessTokenGrant, AccessTokenRecord, AccessTokenResource } from "./store.js";
|
|
2
|
+
/** The default token prefix: "Cardón access token". */
|
|
3
|
+
export declare const DEFAULT_PREFIX = "cat";
|
|
4
|
+
/** Lowercase letters and digits, 2 to 12 characters. */
|
|
5
|
+
export declare const PREFIX: RegExp;
|
|
6
|
+
/** Random bytes in a token: 256 bits. */
|
|
7
|
+
export declare const TOKEN_BYTES = 32;
|
|
8
|
+
/** Length of {@link TOKEN_BYTES} as unpadded base64url. */
|
|
9
|
+
export declare const TOKEN_SECRET_LENGTH = 43;
|
|
10
|
+
/** Most scopes one token may carry. */
|
|
11
|
+
export declare const MAX_SCOPES = 32;
|
|
12
|
+
export declare function isResourceType(value: unknown): value is string;
|
|
13
|
+
export declare function isResourceId(value: unknown): value is string;
|
|
14
|
+
export declare function isScope(value: unknown): value is string;
|
|
15
|
+
/** True for a well-formed resource. Never echoes the value in errors built from it. */
|
|
16
|
+
export declare function isResource(value: unknown): value is AccessTokenResource;
|
|
17
|
+
/** Throws a `TypeError` (without the value) unless `value` is a well-formed resource. */
|
|
18
|
+
export declare function assertResource(where: string, value: unknown): asserts value is AccessTokenResource;
|
|
19
|
+
/**
|
|
20
|
+
* The scopes without duplicates, in their order. Throws a `TypeError` unless a non-empty array of
|
|
21
|
+
* at most {@link MAX_SCOPES} valid scopes.
|
|
22
|
+
*/
|
|
23
|
+
export declare function checkScopes(where: string, value: unknown): readonly string[];
|
|
24
|
+
/**
|
|
25
|
+
* A copy of the caller's resource, each field read once, so the value validated is the value
|
|
26
|
+
* used. Anything but an object is returned as is (and fails validation).
|
|
27
|
+
*/
|
|
28
|
+
export declare function copyResource(value: unknown): unknown;
|
|
29
|
+
/** The grant handed to callers: the record without its hash, frozen. */
|
|
30
|
+
export declare function toGrant(record: AccessTokenRecord): AccessTokenGrant;
|
|
31
|
+
/**
|
|
32
|
+
* A frozen copy of a record a store returned, or `undefined` when it is malformed (a store bug:
|
|
33
|
+
* the caller treats it as a store failure, never as a pass).
|
|
34
|
+
*/
|
|
35
|
+
export declare function toRecord(value: unknown): AccessTokenRecord | undefined;
|
|
36
|
+
//# sourceMappingURL=validation.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAE3F,uDAAuD;AACvD,eAAO,MAAM,cAAc,QAAQ,CAAC;AACpC,wDAAwD;AACxD,eAAO,MAAM,MAAM,QAAqB,CAAC;AACzC,yCAAyC;AACzC,eAAO,MAAM,WAAW,KAAK,CAAC;AAC9B,2DAA2D;AAC3D,eAAO,MAAM,mBAAmB,KAAK,CAAC;AAMtC,uCAAuC;AACvC,eAAO,MAAM,UAAU,KAAK,CAAC;AAE7B,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAE9D;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAE5D;AAED,wBAAgB,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAEvD;AAED,uFAAuF;AACvF,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,mBAAmB,CAIvE;AAED,yFAAyF;AACzF,wBAAgB,cAAc,CAC5B,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,OAAO,GACb,OAAO,CAAC,KAAK,IAAI,mBAAmB,CAgBtC;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,SAAS,MAAM,EAAE,CAkB5E;AAMD;;;GAGG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAIpD;AAED,wEAAwE;AACxE,wBAAgB,OAAO,CAAC,MAAM,EAAE,iBAAiB,GAAG,gBAAgB,CAUnE;AAED;;;GAGG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,iBAAiB,GAAG,SAAS,CAoBtE"}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/** The default token prefix: "Cardón access token". */
|
|
2
|
+
export const DEFAULT_PREFIX = "cat";
|
|
3
|
+
/** Lowercase letters and digits, 2 to 12 characters. */
|
|
4
|
+
export const PREFIX = /^[a-z0-9]{2,12}$/;
|
|
5
|
+
/** Random bytes in a token: 256 bits. */
|
|
6
|
+
export const TOKEN_BYTES = 32;
|
|
7
|
+
/** Length of {@link TOKEN_BYTES} as unpadded base64url. */
|
|
8
|
+
export const TOKEN_SECRET_LENGTH = 43;
|
|
9
|
+
const RESOURCE_TYPE = /^[a-z][a-z0-9_.-]{0,63}$/;
|
|
10
|
+
const RESOURCE_ID = /^[\x21-\x7e]{1,255}$/;
|
|
11
|
+
const SCOPE = /^[a-z0-9][a-z0-9:._-]{0,63}$/;
|
|
12
|
+
const HASH = /^[0-9a-f]{64}$/;
|
|
13
|
+
/** Most scopes one token may carry. */
|
|
14
|
+
export const MAX_SCOPES = 32;
|
|
15
|
+
export function isResourceType(value) {
|
|
16
|
+
return typeof value === "string" && RESOURCE_TYPE.test(value);
|
|
17
|
+
}
|
|
18
|
+
export function isResourceId(value) {
|
|
19
|
+
return typeof value === "string" && RESOURCE_ID.test(value);
|
|
20
|
+
}
|
|
21
|
+
export function isScope(value) {
|
|
22
|
+
return typeof value === "string" && SCOPE.test(value);
|
|
23
|
+
}
|
|
24
|
+
/** True for a well-formed resource. Never echoes the value in errors built from it. */
|
|
25
|
+
export function isResource(value) {
|
|
26
|
+
if (typeof value !== "object" || value === null)
|
|
27
|
+
return false;
|
|
28
|
+
const { type, id } = value;
|
|
29
|
+
return isResourceType(type) && isResourceId(id);
|
|
30
|
+
}
|
|
31
|
+
/** Throws a `TypeError` (without the value) unless `value` is a well-formed resource. */
|
|
32
|
+
export function assertResource(where, value) {
|
|
33
|
+
if (typeof value !== "object" || value === null) {
|
|
34
|
+
throw new TypeError(`${where}: resource must be an object { type, id }.`);
|
|
35
|
+
}
|
|
36
|
+
const { type, id } = value;
|
|
37
|
+
if (!isResourceType(type)) {
|
|
38
|
+
throw new TypeError(`${where}: resource.type must be 1 to 64 lowercase letters, digits, "_", "." or "-", ` +
|
|
39
|
+
"starting with a letter.");
|
|
40
|
+
}
|
|
41
|
+
if (!isResourceId(id)) {
|
|
42
|
+
throw new TypeError(`${where}: resource.id must be 1 to 255 printable ASCII characters without spaces.`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The scopes without duplicates, in their order. Throws a `TypeError` unless a non-empty array of
|
|
47
|
+
* at most {@link MAX_SCOPES} valid scopes.
|
|
48
|
+
*/
|
|
49
|
+
export function checkScopes(where, value) {
|
|
50
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
51
|
+
throw new TypeError(`${where}: scopes must be a non-empty array of scope strings.`);
|
|
52
|
+
}
|
|
53
|
+
if (value.length > MAX_SCOPES) {
|
|
54
|
+
throw new TypeError(`${where}: at most ${MAX_SCOPES} scopes per token.`);
|
|
55
|
+
}
|
|
56
|
+
// Read the caller's array once: what is validated is what is stored.
|
|
57
|
+
const scopes = [...value];
|
|
58
|
+
for (const scope of scopes) {
|
|
59
|
+
if (!isScope(scope)) {
|
|
60
|
+
throw new TypeError(`${where}: each scope must be 1 to 64 lowercase letters, digits, ":", "_", "." or "-", ` +
|
|
61
|
+
'starting with a letter or digit, e.g. "order:read".');
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return Object.freeze([...new Set(scopes)]);
|
|
65
|
+
}
|
|
66
|
+
function isDate(value) {
|
|
67
|
+
return value instanceof Date && !Number.isNaN(value.getTime());
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* A copy of the caller's resource, each field read once, so the value validated is the value
|
|
71
|
+
* used. Anything but an object is returned as is (and fails validation).
|
|
72
|
+
*/
|
|
73
|
+
export function copyResource(value) {
|
|
74
|
+
if (typeof value !== "object" || value === null)
|
|
75
|
+
return value;
|
|
76
|
+
const { type, id } = value;
|
|
77
|
+
return { type, id };
|
|
78
|
+
}
|
|
79
|
+
/** The grant handed to callers: the record without its hash, frozen. */
|
|
80
|
+
export function toGrant(record) {
|
|
81
|
+
return Object.freeze({
|
|
82
|
+
id: record.id,
|
|
83
|
+
resourceType: record.resourceType,
|
|
84
|
+
resourceId: record.resourceId,
|
|
85
|
+
scopes: record.scopes,
|
|
86
|
+
createdAt: new Date(record.createdAt.getTime()),
|
|
87
|
+
expiresAt: new Date(record.expiresAt.getTime()),
|
|
88
|
+
...(record.revokedAt === undefined ? {} : { revokedAt: new Date(record.revokedAt.getTime()) }),
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* A frozen copy of a record a store returned, or `undefined` when it is malformed (a store bug:
|
|
93
|
+
* the caller treats it as a store failure, never as a pass).
|
|
94
|
+
*/
|
|
95
|
+
export function toRecord(value) {
|
|
96
|
+
if (typeof value !== "object" || value === null)
|
|
97
|
+
return undefined;
|
|
98
|
+
const { id, tokenHash, resourceType, resourceId, scopes, createdAt, expiresAt, revokedAt } = value;
|
|
99
|
+
if (typeof id !== "string" || id === "")
|
|
100
|
+
return undefined;
|
|
101
|
+
if (typeof tokenHash !== "string" || !HASH.test(tokenHash))
|
|
102
|
+
return undefined;
|
|
103
|
+
if (!isResourceType(resourceType) || !isResourceId(resourceId))
|
|
104
|
+
return undefined;
|
|
105
|
+
if (!Array.isArray(scopes) || scopes.length === 0 || !scopes.every(isScope))
|
|
106
|
+
return undefined;
|
|
107
|
+
if (!isDate(createdAt) || !isDate(expiresAt))
|
|
108
|
+
return undefined;
|
|
109
|
+
if (revokedAt !== undefined && revokedAt !== null && !isDate(revokedAt))
|
|
110
|
+
return undefined;
|
|
111
|
+
return Object.freeze({
|
|
112
|
+
id,
|
|
113
|
+
tokenHash,
|
|
114
|
+
resourceType,
|
|
115
|
+
resourceId,
|
|
116
|
+
scopes: Object.freeze([...scopes]),
|
|
117
|
+
createdAt: new Date(createdAt.getTime()),
|
|
118
|
+
expiresAt: new Date(expiresAt.getTime()),
|
|
119
|
+
...(isDate(revokedAt) ? { revokedAt: new Date(revokedAt.getTime()) } : {}),
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
//# sourceMappingURL=validation.js.map
|
|
@@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EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC3E,CAAC,CAAC;AACL,CAAC"}
|
package/llms.txt
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# @cardonjs/access-tokens
|
|
2
|
+
|
|
3
|
+
Unguessable, expiring, revocable tokens that grant scoped access to one resource without an
|
|
4
|
+
account (a guest's order, an invoice link, an invitation, a share link). `accessTokens` issues,
|
|
5
|
+
verifies and revokes them over an `AccessTokenStore`; `requireAccessToken` is a Hono middleware
|
|
6
|
+
that authorises a route with a token read only from a header. Generic: resource types, scopes,
|
|
7
|
+
lifetimes and routes stay in the project. Standard web APIs only.
|
|
8
|
+
|
|
9
|
+
Full documentation: README.md in this package.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
pnpm add @cardonjs/access-tokens @cardonjs/core hono
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Required peers: `@cardonjs/core`, `hono`. The D1 store is `@cardonjs/db-d1/access-tokens`.
|
|
18
|
+
|
|
19
|
+
## Exports
|
|
20
|
+
|
|
21
|
+
### `@cardonjs/access-tokens`
|
|
22
|
+
|
|
23
|
+
- `accessTokens({ store, prefix?, defaultTtl?, maxTtl?, now? })`: returns `AccessTokens`.
|
|
24
|
+
`prefix` is 2 to 12 lowercase letters or digits (default `"cat"`); `defaultTtl` default `"1d"`;
|
|
25
|
+
`maxTtl` default `"30d"`, at most `"366d"`. A `Duration` is whole seconds or `"15m"`, `"12h"`,
|
|
26
|
+
`"7d"`. Throws a `TypeError` for invalid options.
|
|
27
|
+
- `AccessTokens.issue({ resource: { type, id }, scopes, ttl? })`: resolves `{ token, record }`
|
|
28
|
+
(`record` is an `AccessTokenGrant`: the stored record without `tokenHash`).
|
|
29
|
+
The token is `<prefix>_<43 base64url chars>` (32 random bytes); only its SHA-256 is stored.
|
|
30
|
+
`ttl` above `maxTtl` throws. Resource type: lowercase letters, digits, `_.-`, starting with a
|
|
31
|
+
letter, ≤ 64; id: 1 to 255 printable ASCII without spaces; scopes: 1 to 32 of
|
|
32
|
+
`[a-z0-9][a-z0-9:._-]{0,63}`.
|
|
33
|
+
- `AccessTokens.verify(token)`: `{ ok: true, record }` (an `AccessTokenGrant`) or `{ ok: false, reason }` with
|
|
34
|
+
`"missing" | "invalid" | "expired" | "revoked"`. Rejects when the store fails.
|
|
35
|
+
- `AccessTokens.revoke(id)`, `revokeForResource({ type, id })`, `purgeExpired({ olderThan? })`.
|
|
36
|
+
- `requireAccessToken(tokens | (c) => tokens, { resource, scope, header?, optional? })`:
|
|
37
|
+
`resource` is `{ type, param }` (path parameter) or `(c) => ({ type, id })`; `scope` is one
|
|
38
|
+
scope or a list (all needed); `header` default `Authorization` (`Bearer <token>`), any other
|
|
39
|
+
header carries the bare token. Sets `c.var.accessToken` (the `AccessTokenGrant`, no hash). Every failure is the same
|
|
40
|
+
`401 UNAUTHORIZED` with `WWW-Authenticate`; a store failure is `503`. Registers the
|
|
41
|
+
`accessToken` OpenAPI security scheme and the 401/503 responses.
|
|
42
|
+
- `accessTokenSecurityScheme(header?)`, `ACCESS_TOKEN_SECURITY_SCHEME` (`"accessToken"`),
|
|
43
|
+
`hashAccessToken(token)`.
|
|
44
|
+
- Types: `AccessTokens`, `AccessTokensOptions`, `AccessTokenGrant`, `AccessTokenRecord` (the
|
|
45
|
+
store's: grant plus `tokenHash`), `AccessTokenResource`,
|
|
46
|
+
`AccessTokenStore`, `AccessTokenVerification`, `AccessTokenFailure`, `AccessTokenVariables`,
|
|
47
|
+
`Duration`, `IssueAccessTokenInput`, `IssuedAccessToken`, `PurgeExpiredOptions`,
|
|
48
|
+
`RequireAccessTokenOptions`, `AccessTokenResourceSelector`.
|
|
49
|
+
|
|
50
|
+
### `@cardonjs/access-tokens/testing`
|
|
51
|
+
|
|
52
|
+
- `memoryAccessTokenStore()`: an in-memory `AccessTokenStore` for tests.
|
|
53
|
+
|
|
54
|
+
## Minimal example
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { requireAuth } from "@cardonjs/auth";
|
|
58
|
+
import { accessTokens, requireAccessToken } from "@cardonjs/access-tokens";
|
|
59
|
+
import { type CardonEnv, createApp, ok, UnauthorizedError } from "@cardonjs/core";
|
|
60
|
+
import { d1Database } from "@cardonjs/db-d1";
|
|
61
|
+
import { d1AccessTokenStore } from "@cardonjs/db-d1/access-tokens";
|
|
62
|
+
import { createRoute, z } from "@hono/zod-openapi";
|
|
63
|
+
|
|
64
|
+
type Bindings = { DB: D1Database };
|
|
65
|
+
const adapters = (env: Bindings) => {
|
|
66
|
+
const db = d1Database(env.DB, { schema });
|
|
67
|
+
return {
|
|
68
|
+
auth: sessionAuth(env),
|
|
69
|
+
tokens: accessTokens({ store: d1AccessTokenStore(db.client), prefix: "ord", maxTtl: "30d" }),
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
type AppEnv = CardonEnv<Bindings, ReturnType<typeof adapters>>;
|
|
73
|
+
|
|
74
|
+
const app = createApp(adapters, {
|
|
75
|
+
guard: requireAuth<AppEnv>({
|
|
76
|
+
authenticator: (c) => c.var.adapters.auth,
|
|
77
|
+
public: ["GET /v1/orders/:id"], // the token authorises it
|
|
78
|
+
}),
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
const getOrder = createRoute({
|
|
82
|
+
method: "get",
|
|
83
|
+
path: "/v1/orders/{id}",
|
|
84
|
+
tags: ["Orders"],
|
|
85
|
+
summary: "Get an order with its access token",
|
|
86
|
+
middleware: requireAccessToken<AppEnv>((c) => c.var.adapters.tokens, {
|
|
87
|
+
resource: { type: "order", param: "id" },
|
|
88
|
+
scope: "order:read",
|
|
89
|
+
}),
|
|
90
|
+
request: { params: z.object({ id: z.string() }) },
|
|
91
|
+
responses: { 200: { description: "The order" } },
|
|
92
|
+
});
|
|
93
|
+
app.openapi(getOrder, (c) => {
|
|
94
|
+
const grant = c.var.accessToken;
|
|
95
|
+
if (grant === undefined) throw new UnauthorizedError(); // fail closed
|
|
96
|
+
return ok(c, { id: grant.resourceId });
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// When the order is placed (return `token` once, never log it):
|
|
100
|
+
// const { token } = await c.var.adapters.tokens.issue({
|
|
101
|
+
// resource: { type: "order", id: order.id }, scopes: ["order:read"], ttl: "7d" });
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Rules and common mistakes
|
|
105
|
+
|
|
106
|
+
- Never put a token in a URL query string or path: the middleware reads only the header. For
|
|
107
|
+
links (email, QR), use the fragment, `https://app.example/orders/42#token=…`, and have the web
|
|
108
|
+
app send it in the header.
|
|
109
|
+
- List token routes as public in `requireAuth`; the middleware is their authorisation.
|
|
110
|
+
**A route listed as public without `requireAccessToken` (forgotten, or in the wrong
|
|
111
|
+
`createRoute` object) is fully open.** Add a route test that expects 401 with no header, and
|
|
112
|
+
have handlers read `c.var.accessToken` and fail closed when it is undefined on non-optional
|
|
113
|
+
routes.
|
|
114
|
+
- Every token expires; pick `ttl` per use and keep `maxTtl` short.
|
|
115
|
+
- Never log, store or echo the token; `issue` returns it once.
|
|
116
|
+
- Add a rate limit per IP (`rateLimit` with `rateLimitKeys.ip`) to routes that take or issue
|
|
117
|
+
tokens.
|
|
118
|
+
- `scope` is required: a route always names what the token must allow.
|
|
119
|
+
- `optional: true` passes requests without a token. For "a token or a signed-in user", list the
|
|
120
|
+
route in `requireAuth({ optional: ["GET /v1/orders/:id"] })` (not `public`): the guard
|
|
121
|
+
authenticates a presented credential and lets a caller without one through. In the handler,
|
|
122
|
+
serve the grant first; otherwise `getIdentity(c)` (401 when nobody signed in, fail closed),
|
|
123
|
+
then check that the identity may act on the resource. **The guard runs before
|
|
124
|
+
`requireAccessToken`**: an authenticator reading `Authorization: Bearer` answers 401 to an
|
|
125
|
+
access token there (a bad credential is never downgraded), so take the token in a custom
|
|
126
|
+
header (`header: "X-Order-Token"`); one reading a cookie (`@cardonjs/users`) or its own header
|
|
127
|
+
leaves `Authorization` to the token. Declare `security: [{ <session scheme>: [] },
|
|
128
|
+
{ accessToken: [] }, {}]` on the `createRoute` to document both. With
|
|
129
|
+
`Authorization`, only a value without `<prefix>_` anywhere counts as no token; one containing it
|
|
130
|
+
must be exactly `Bearer <one valid token>` or it is a 401. A custom header must hold exactly one
|
|
131
|
+
valid token.
|
|
132
|
+
- Links: disable email click tracking for messages carrying them (trackers embed the full URL,
|
|
133
|
+
fragment included); drop the fragment with `history.replaceState` before any analytics or
|
|
134
|
+
third-party script reads `location`; the token stays in the email/chat and link-preview caches,
|
|
135
|
+
so use short TTLs and revoke when done; serve the page with `Referrer-Policy: no-referrer`
|
|
136
|
+
(the path holds the resource id).
|
|
137
|
+
- Revoke with `revokeForResource` when the resource no longer needs guest access; purge expired
|
|
138
|
+
records hourly with `purgeExpired`.
|
|
139
|
+
- Store implementations pass `accessTokenStoreContract` from `@cardonjs/testing`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cardonjs/access-tokens",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.3",
|
|
4
|
+
"description": "Access tokens for Cardón apps: unguessable, expiring, revocable tokens that grant scoped access to one resource without an account, a header-only Hono middleware, the store interface and an OpenAPI security scheme.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/cardonjs/cardon.git",
|
|
9
|
+
"directory": "packages/access-tokens"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/cardonjs/cardon/tree/main/packages/access-tokens#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/cardonjs/cardon/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./testing": {
|
|
23
|
+
"types": "./dist/testing.d.ts",
|
|
24
|
+
"default": "./dist/testing.js"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"dist",
|
|
29
|
+
"llms.txt"
|
|
30
|
+
],
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"hono": "^4.13.18",
|
|
36
|
+
"@cardonjs/core": "^0.5.1"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@hono/zod-openapi": "1.6.3",
|
|
40
|
+
"@scalar/hono-api-reference": "0.12.20",
|
|
41
|
+
"hono": "4.13.18",
|
|
42
|
+
"typescript": "7.0.2",
|
|
43
|
+
"vitest": "5.1.0",
|
|
44
|
+
"zod": "4.6.7",
|
|
45
|
+
"@cardonjs/auth": "0.2.6",
|
|
46
|
+
"@cardonjs/config": "0.0.0",
|
|
47
|
+
"@cardonjs/testing": "0.6.0",
|
|
48
|
+
"@cardonjs/core": "0.5.1"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"build": "tsc -p tsconfig.build.json",
|
|
52
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
53
|
+
"test": "vitest run"
|
|
54
|
+
}
|
|
6
55
|
}
|