@superintelligentfamily/key-verify 0.0.0-stage → 0.1.0

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Seth Shoultes
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/lib/index.d.ts ADDED
@@ -0,0 +1,89 @@
1
+ import { type JWTPayload } from "jose";
2
+ export declare const PACKAGE_NAME = "@superintelligentfamily/key-verify";
3
+ /** No token was sent. */
4
+ export declare class TokenMissing extends Error {
5
+ name: string;
6
+ }
7
+ /** The token isn't a valid Key access token for this audience. */
8
+ export declare class TokenInvalid extends Error {
9
+ name: string;
10
+ }
11
+ /** The token was valid and has expired. */
12
+ export declare class TokenExpired extends Error {
13
+ name: string;
14
+ }
15
+ /** The user signed out everywhere, or was suspended or deleted, after the token was minted. */
16
+ export declare class Revoked extends Error {
17
+ name: string;
18
+ }
19
+ /** Key's keys or the marker couldn't be read, and nothing cached stands in: answer 503. */
20
+ export declare class Unavailable extends Error {
21
+ name: string;
22
+ }
23
+ export interface Marker {
24
+ jwt_version: number;
25
+ revoked_after: number;
26
+ }
27
+ /** The one KV call used, so any binding with `get` fits (a Workers KVNamespace does). */
28
+ export interface MarkerStore {
29
+ get(key: string): Promise<string | null>;
30
+ }
31
+ export interface VerifierOptions {
32
+ /** Key's issuer, e.g. https://auth.superintelligentkey.com, or an app's own https://auth.…/a/<app_id> (DESIGN §3.2 [F3]). */
33
+ issuer: string;
34
+ /** Key's JWKS; by default the one at the issuer's origin, which every issuer path shares (DESIGN §3.2). */
35
+ jwksUri?: string;
36
+ /** This app's id: tokens for any other app are refused. Or a resource's URL, such as the Key API's, for a client that
37
+ * asked for that resource (RFC 8707): then `markerClient` names the client. */
38
+ audience: string;
39
+ /** The client whose secret key reads the marker from the API; this app's id, so by default the audience. */
40
+ markerClient?: string;
41
+ /** True for an audience whose tokens carry no plans (Key's platform tokens for its API, doorman#66): a token with no
42
+ * plans claim reads as plans [], so requirePlans refuses it. A plans claim that is there is still checked. */
43
+ planless?: boolean;
44
+ /** Where the marker comes from: Key's KV binding, or the API with this app's secret key. */
45
+ markers: {
46
+ kv: MarkerStore;
47
+ } | {
48
+ api: string;
49
+ secretKey: string;
50
+ };
51
+ /** Seconds since the epoch; for tests. */
52
+ now?: () => number;
53
+ /** For tests and runtimes without a global fetch. */
54
+ fetch?: typeof fetch;
55
+ }
56
+ export interface Claims extends JWTPayload {
57
+ sub: string;
58
+ iat: number;
59
+ exp: number;
60
+ jwt_version: number;
61
+ sid: string;
62
+ plans: string[];
63
+ /** When each plan began, in unix seconds (doorman#136, drip content). A token minted before Key sent it reads as {}, so
64
+ * a drip gate finds no start and refuses. */
65
+ plan_started: Record<string, number>;
66
+ }
67
+ /** A marker is cached this long per user: a revocation shuts a token out within it (DESIGN §5.4, M4's 60 seconds). */
68
+ export declare const MARKER_TTL = 60;
69
+ /** At most this many users' markers are cached; past it the cache starts again (Fable on #56: it never grows unbounded). */
70
+ export declare const MARKER_CACHE_MAX = 10000;
71
+ /** Key's JWKS is cached as its Cache-Control says (DESIGN §3.1), and refetched for an unknown kid at most this often. */
72
+ export declare const JWKS_TTL = 3600;
73
+ export declare const JWKS_COOLDOWN = 60;
74
+ /** Clock difference allowed between Key and this server, both ways: exp, and a refused iat from the future. */
75
+ export declare const CLOCK_SKEW = 30;
76
+ /** plan_started as Key mints it (doorman#136): a plain object whose keys are slugs of this token's own plans and whose
77
+ * values are whole unix seconds, no later than the token itself was minted. So no own "__proto__" or "constructor" key,
78
+ * no odd, empty or unheld slug, no more keys than plans, and no 1e300, 2^53+2 or year-9999 start (maint-review and
79
+ * mi-dev-4 on #137). */
80
+ /** At most this many plans' starts in one token: far more than any site has plans. */
81
+ export declare const MAX_PLAN_STARTS = 64;
82
+ export declare function createVerifier(o: VerifierOptions): {
83
+ verify: (token: string | null | undefined) => Promise<Claims>;
84
+ verifyIdToken: (token: string | null | undefined, nonce: string) => Promise<JWTPayload & {
85
+ sub: string;
86
+ nonce: string;
87
+ }>;
88
+ requirePlans: (claims: Claims, slugs: string[]) => boolean;
89
+ };
package/lib/index.js ADDED
@@ -0,0 +1,187 @@
1
+ // @superintelligentfamily/key-verify (DESIGN §6.3, §5.4): checks a Key access token on a site's or an app's server. ES256 against Key's
2
+ // JWKS (cached an hour, refetched once on an unknown kid, at most once a minute), then iss, aud, exp and typ at+jwt,
3
+ // then the user's revocation marker: KV when the binding is there (Key's own account), otherwise the API's
4
+ // GET /v1/markers/<sub> with the app's secret key, cached 60 seconds. A failed key or marker
5
+ // read throws Unavailable, which a gate answers with a 503, never by letting the token through.
6
+ import { createLocalJWKSet, errors, jwtVerify } from "jose";
7
+ export const PACKAGE_NAME = "@superintelligentfamily/key-verify";
8
+ /** No token was sent. */
9
+ export class TokenMissing extends Error {
10
+ name = "TokenMissing";
11
+ }
12
+ /** The token isn't a valid Key access token for this audience. */
13
+ export class TokenInvalid extends Error {
14
+ name = "TokenInvalid";
15
+ }
16
+ /** The token was valid and has expired. */
17
+ export class TokenExpired extends Error {
18
+ name = "TokenExpired";
19
+ }
20
+ /** The user signed out everywhere, or was suspended or deleted, after the token was minted. */
21
+ export class Revoked extends Error {
22
+ name = "Revoked";
23
+ }
24
+ /** Key's keys or the marker couldn't be read, and nothing cached stands in: answer 503. */
25
+ export class Unavailable extends Error {
26
+ name = "Unavailable";
27
+ }
28
+ /** A marker is cached this long per user: a revocation shuts a token out within it (DESIGN §5.4, M4's 60 seconds). */
29
+ export const MARKER_TTL = 60;
30
+ /** At most this many users' markers are cached; past it the cache starts again (Fable on #56: it never grows unbounded). */
31
+ export const MARKER_CACHE_MAX = 10_000;
32
+ /** Key's JWKS is cached as its Cache-Control says (DESIGN §3.1), and refetched for an unknown kid at most this often. */
33
+ export const JWKS_TTL = 3600;
34
+ export const JWKS_COOLDOWN = 60;
35
+ /** Clock difference allowed between Key and this server, both ways: exp, and a refused iat from the future. */
36
+ export const CLOCK_SKEW = 30;
37
+ /** A plan slug as Key makes it (the members plugin's SLUG). */
38
+ const SLUG = /^[a-z0-9][a-z0-9_-]{0,63}$/;
39
+ /** plan_started as Key mints it (doorman#136): a plain object whose keys are slugs of this token's own plans and whose
40
+ * values are whole unix seconds, no later than the token itself was minted. So no own "__proto__" or "constructor" key,
41
+ * no odd, empty or unheld slug, no more keys than plans, and no 1e300, 2^53+2 or year-9999 start (maint-review and
42
+ * mi-dev-4 on #137). */
43
+ /** At most this many plans' starts in one token: far more than any site has plans. */
44
+ export const MAX_PLAN_STARTS = 64;
45
+ const RESERVED = new Set(["__proto__", "constructor", "prototype"]);
46
+ const isPlanStarted = (v, plans, iat) => typeof v === "object" && v !== null && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype &&
47
+ Object.keys(v).length <= MAX_PLAN_STARTS &&
48
+ Object.entries(v).every(([k, n]) => !RESERVED.has(k) && SLUG.test(k) && plans.includes(k) &&
49
+ Number.isSafeInteger(n) && n >= 0 && n <= iat);
50
+ const isMarker = (m) => !!m && typeof m === "object" && Number.isInteger(m.jwt_version) && Number.isInteger(m.revoked_after);
51
+ export function createVerifier(o) {
52
+ const now = o.now ?? (() => Math.floor(Date.now() / 1000));
53
+ const get = o.fetch ?? ((...a) => fetch(...a));
54
+ const jwksUri = o.jwksUri ?? `${new URL(o.issuer).origin}/.well-known/jwks.json`;
55
+ let keys = null;
56
+ /** One JWKS fetch at a time: verifies that arrive together share it (Fable on #56). */
57
+ let inFlight = null;
58
+ /** Key's published keys, fetched here so that any failure to read them is Unavailable, never a bad token. */
59
+ async function keysFor(kid) {
60
+ const t = now();
61
+ const stale = !keys || t - keys.at >= JWKS_TTL || (kid !== undefined && !keys.kids.has(kid) && t - keys.at >= JWKS_COOLDOWN);
62
+ if (!stale && keys)
63
+ return keys.set;
64
+ inFlight ??= (async () => {
65
+ try {
66
+ const res = await get(jwksUri, { headers: { accept: "application/json" } });
67
+ const body = res.ok ? await res.json() : null;
68
+ if (!body || !Array.isArray(body.keys))
69
+ throw new Error(`the JWKS answered ${res.status}`);
70
+ const set = body;
71
+ // Built inside the try: a 200 that isn't a key set is Unavailable too, never a bad token (Fable on #56).
72
+ keys = { set: createLocalJWKSet(set), kids: new Set(set.keys.map((k) => k.kid ?? "")), at: t };
73
+ return keys.set;
74
+ }
75
+ catch (e) {
76
+ throw new Unavailable(`Key's keys couldn't be read: ${e instanceof Error ? e.message : String(e)}`);
77
+ }
78
+ finally {
79
+ inFlight = null;
80
+ }
81
+ })();
82
+ return inFlight;
83
+ }
84
+ const cache = new Map();
85
+ /** The user's marker, or null when the user is no longer this app's (which reads as revoked). */
86
+ async function readMarker(sub) {
87
+ const m = o.markers;
88
+ if ("kv" in m) {
89
+ let raw;
90
+ try {
91
+ raw = await m.kv.get(`m:${sub}`);
92
+ }
93
+ catch (e) {
94
+ throw new Unavailable(`the marker store can't be read: ${String(e)}`);
95
+ }
96
+ if (raw === null)
97
+ return { jwt_version: 0, revoked_after: 0 }; // no marker: nothing was ever revoked
98
+ let parsed;
99
+ try {
100
+ parsed = JSON.parse(raw);
101
+ }
102
+ catch {
103
+ throw new Unavailable("the marker store holds a value that isn't a marker");
104
+ }
105
+ if (!isMarker(parsed))
106
+ throw new Unavailable("the marker store holds a value that isn't a marker");
107
+ return parsed;
108
+ }
109
+ const t = now(), hit = cache.get(sub);
110
+ if (hit && hit.until > t)
111
+ return hit.m;
112
+ if (hit)
113
+ cache.delete(sub);
114
+ try {
115
+ const res = await get(`${m.api}/v1/markers/${encodeURIComponent(sub)}`, {
116
+ headers: { authorization: `Basic ${btoa(`${encodeURIComponent(o.markerClient ?? o.audience)}:${encodeURIComponent(m.secretKey)}`)}`, accept: "application/json" },
117
+ });
118
+ let fresh;
119
+ if (res.status === 404)
120
+ fresh = null;
121
+ else {
122
+ const body = res.ok ? await res.json() : null;
123
+ if (!isMarker(body))
124
+ throw new Error(`the API answered ${res.status}`);
125
+ fresh = body;
126
+ }
127
+ if (cache.size >= MARKER_CACHE_MAX)
128
+ cache.clear();
129
+ cache.set(sub, { m: fresh, until: t + MARKER_TTL });
130
+ return fresh;
131
+ }
132
+ catch (e) {
133
+ // An expired cached answer never stands in: a revoked user would keep getting in while the API is down.
134
+ throw new Unavailable(`the marker couldn't be read: ${e instanceof Error ? e.message : String(e)}`);
135
+ }
136
+ }
137
+ /** The token's payload once its signature, typ, iss, aud and times pass; errors mapped to the typed ones. */
138
+ async function checked(token, typ) {
139
+ if (!token)
140
+ throw new TokenMissing("no token");
141
+ let payload;
142
+ try {
143
+ ({ payload } = await jwtVerify(token, async (header, tok) => (await keysFor(header.kid))(header, tok), {
144
+ issuer: o.issuer, audience: o.audience, algorithms: ["ES256"], typ, currentDate: new Date(now() * 1000),
145
+ requiredClaims: ["sub", "iat", "exp"], clockTolerance: CLOCK_SKEW,
146
+ }));
147
+ }
148
+ catch (e) {
149
+ if (e instanceof Unavailable)
150
+ throw e;
151
+ if (e instanceof errors.JWTExpired)
152
+ throw new TokenExpired("the token has expired");
153
+ throw new TokenInvalid(e instanceof Error ? e.message : String(e));
154
+ }
155
+ if (typeof payload.iat === "number" && payload.iat > now() + CLOCK_SKEW)
156
+ throw new TokenInvalid("the token says it was minted in the future");
157
+ return payload;
158
+ }
159
+ async function verify(token) {
160
+ const c = (await checked(token, "at+jwt"));
161
+ if (o.planless && c.plans === undefined)
162
+ c.plans = [];
163
+ if (typeof c.sub !== "string" || !Number.isInteger(c.jwt_version) || typeof c.iat !== "number" || !Array.isArray(c.plans) || !c.plans.every((p) => typeof p === "string")) {
164
+ throw new TokenInvalid("the token lacks Key's access-token claims");
165
+ }
166
+ if (c.plan_started === undefined)
167
+ c.plan_started = {};
168
+ if (!isPlanStarted(c.plan_started, c.plans, c.iat))
169
+ throw new TokenInvalid("the token's plan_started isn't {held plan slug: unix seconds}");
170
+ const m = await readMarker(c.sub);
171
+ // <= so a token minted in the same second as "sign out everywhere" is revoked too (DESIGN §5.4).
172
+ if (!m || c.jwt_version < m.jwt_version || c.iat <= m.revoked_after)
173
+ throw new Revoked("the user's sessions were revoked after this token was minted");
174
+ return c;
175
+ }
176
+ /** An ID token from this app's own code exchange (DESIGN §3.2): typ JWT, and the nonce this sign-in sent. No marker:
177
+ * it is checked once, at the callback, beside the access token that `verify` checks. */
178
+ async function verifyIdToken(token, nonce) {
179
+ const p = await checked(token, "JWT");
180
+ if (!nonce || p.nonce !== nonce)
181
+ throw new TokenInvalid("the ID token's nonce isn't this sign-in's");
182
+ return p;
183
+ }
184
+ /** True when the token's plans hold at least one of these slugs. */
185
+ const requirePlans = (claims, slugs) => slugs.some((s) => claims.plans.includes(s));
186
+ return { verify, verifyIdToken, requirePlans };
187
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@superintelligentfamily/key-verify",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "license": "MIT",
5
+ "description": "Check a Key access token on your server: ES256 against Key's keys, then issuer, audience, expiry and the user's revocation marker.",
6
+ "homepage": "https://superintelligentkey.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/sethshoultes/doorman.git",
10
+ "directory": "packages/verify"
11
+ },
12
+ "type": "module",
13
+ "files": [
14
+ "lib",
15
+ "LICENSE"
16
+ ],
17
+ "exports": {
18
+ ".": {
19
+ "types": "./lib/index.d.ts",
20
+ "import": "./lib/index.js"
21
+ }
22
+ },
23
+ "dependencies": {
24
+ "jose": "6.2.12"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public",
28
+ "provenance": true
29
+ },
30
+ "scripts": {
31
+ "typecheck": "tsc --noEmit -p .",
32
+ "lint": "eslint .",
33
+ "test": "vitest run",
34
+ "check": "pnpm run typecheck && pnpm run lint && pnpm run test",
35
+ "build:npm": "tsc -p tsconfig.build.json"
36
+ }
6
37
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.