@superjackfruitlabs/treaty-ecosystem-identity 0.0.13 → 0.0.15
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 +1 -0
- package/corpus/token_vectors.json +1012 -0
- package/dist/access-token.d.ts +58 -0
- package/dist/access-token.js +171 -0
- package/dist/index.d.ts +8 -1
- package/dist/index.js +6 -0
- package/dist/jwks-cache.d.ts +23 -0
- package/dist/jwks-cache.js +69 -0
- package/package.json +4 -1
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** The closed set of refusal codes, the same in every verifier (token_vectors.json). */
|
|
2
|
+
export declare const ACCESS_TOKEN_ERROR_CODES: readonly ["malformed", "bad_algorithm", "missing_kid", "unknown_key", "bad_signature", "wrong_issuer", "wrong_audience", "expired", "not_yet_valid", "issued_in_future", "lifetime_too_long", "missing_claim", "bad_claim", "product_not_enabled"];
|
|
3
|
+
export type AccessTokenErrorCode = (typeof ACCESS_TOKEN_ERROR_CODES)[number];
|
|
4
|
+
/** Why a token was refused. `code` is one of ACCESS_TOKEN_ERROR_CODES. */
|
|
5
|
+
export declare class AccessTokenError extends Error {
|
|
6
|
+
readonly code: AccessTokenErrorCode;
|
|
7
|
+
constructor(code: AccessTokenErrorCode, message?: string);
|
|
8
|
+
}
|
|
9
|
+
export declare const PRINCIPAL_KINDS: readonly ["human", "agent", "service"];
|
|
10
|
+
export type PrincipalKind = (typeof PRINCIPAL_KINDS)[number];
|
|
11
|
+
/** A verified token's claims: the required ones typed, every other claim passed through. */
|
|
12
|
+
export interface AccessTokenClaims {
|
|
13
|
+
readonly [claim: string]: unknown;
|
|
14
|
+
iss: string;
|
|
15
|
+
sub: string;
|
|
16
|
+
aud: string | string[];
|
|
17
|
+
iat: number;
|
|
18
|
+
exp: number;
|
|
19
|
+
nbf?: number;
|
|
20
|
+
jti: string;
|
|
21
|
+
principalKind: PrincipalKind;
|
|
22
|
+
org: string;
|
|
23
|
+
ent: string[];
|
|
24
|
+
mayDispatch: string[];
|
|
25
|
+
mayGrantReach: boolean;
|
|
26
|
+
act?: {
|
|
27
|
+
sub: string;
|
|
28
|
+
};
|
|
29
|
+
email?: string;
|
|
30
|
+
email_verified?: boolean;
|
|
31
|
+
scope?: string;
|
|
32
|
+
amr?: string[];
|
|
33
|
+
orgRole?: string;
|
|
34
|
+
client_id?: string;
|
|
35
|
+
azp?: string;
|
|
36
|
+
sid?: string;
|
|
37
|
+
}
|
|
38
|
+
export interface VerifyAccessTokenOptions {
|
|
39
|
+
/** The issuer's JWKS. Only OKP Ed25519 keys are used; any other key is ignored. */
|
|
40
|
+
jwks: {
|
|
41
|
+
keys: unknown[];
|
|
42
|
+
};
|
|
43
|
+
/** The issuer's base URL, matched exactly. */
|
|
44
|
+
issuer: string;
|
|
45
|
+
/** This consumer's audience: aud must equal it or, as an array, contain it. */
|
|
46
|
+
audience: string;
|
|
47
|
+
/** This consumer's product, which ent must contain. */
|
|
48
|
+
product: string;
|
|
49
|
+
/** Unix seconds. Defaults to the clock. */
|
|
50
|
+
now?: number;
|
|
51
|
+
}
|
|
52
|
+
export declare const LEEWAY_SECONDS = 30;
|
|
53
|
+
export declare const MAX_LIFETIME_SECONDS = 300;
|
|
54
|
+
/**
|
|
55
|
+
* Verifies an access token and returns its claims, or throws AccessTokenError. Every refusal is
|
|
56
|
+
* one of ACCESS_TOKEN_ERROR_CODES; fixtures/ecosystem-identity/token_vectors.json is the test.
|
|
57
|
+
*/
|
|
58
|
+
export declare function verifyAccessToken(token: string, opts: VerifyAccessTokenOptions): Promise<AccessTokenClaims>;
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One access-token verifier for the suite, to the rules in token_claims.json and
|
|
3
|
+
* token_vectors.json: EdDSA over Ed25519 only, a kid required, 30 s of leeway on exp, nbf and
|
|
4
|
+
* iat, a lifetime of at most 300 s, and every required claim in its grammar. It is pure: it takes
|
|
5
|
+
* the JWKS as data, so it runs the same in Workers, Bun and Node, and `now` makes it testable.
|
|
6
|
+
*/
|
|
7
|
+
import { compactVerify, decodeProtectedHeader, importJWK } from "jose";
|
|
8
|
+
/** The closed set of refusal codes, the same in every verifier (token_vectors.json). */
|
|
9
|
+
export const ACCESS_TOKEN_ERROR_CODES = [
|
|
10
|
+
"malformed",
|
|
11
|
+
"bad_algorithm",
|
|
12
|
+
"missing_kid",
|
|
13
|
+
"unknown_key",
|
|
14
|
+
"bad_signature",
|
|
15
|
+
"wrong_issuer",
|
|
16
|
+
"wrong_audience",
|
|
17
|
+
"expired",
|
|
18
|
+
"not_yet_valid",
|
|
19
|
+
"issued_in_future",
|
|
20
|
+
"lifetime_too_long",
|
|
21
|
+
"missing_claim",
|
|
22
|
+
"bad_claim",
|
|
23
|
+
"product_not_enabled",
|
|
24
|
+
];
|
|
25
|
+
/** Why a token was refused. `code` is one of ACCESS_TOKEN_ERROR_CODES. */
|
|
26
|
+
export class AccessTokenError extends Error {
|
|
27
|
+
code;
|
|
28
|
+
constructor(code, message = code) {
|
|
29
|
+
super(message);
|
|
30
|
+
this.name = "AccessTokenError";
|
|
31
|
+
this.code = code;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export const PRINCIPAL_KINDS = ["human", "agent", "service"];
|
|
35
|
+
export const LEEWAY_SECONDS = 30;
|
|
36
|
+
export const MAX_LIFETIME_SECONDS = 300;
|
|
37
|
+
const PRN = /^prn_[0-9a-f]{20}$/;
|
|
38
|
+
const ORG = /^org_[0-9a-f]{20}$/;
|
|
39
|
+
const KINDS = new Set(PRINCIPAL_KINDS);
|
|
40
|
+
const refuse = (code, message) => {
|
|
41
|
+
throw new AccessTokenError(code, message);
|
|
42
|
+
};
|
|
43
|
+
const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
44
|
+
const isStrings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
|
|
45
|
+
/** The Ed25519 key the JWKS holds under `kid`, or undefined. Keys of other kinds are skipped. */
|
|
46
|
+
function ed25519Key(jwks, kid) {
|
|
47
|
+
const keys = Array.isArray(jwks.keys) ? jwks.keys : [];
|
|
48
|
+
return keys
|
|
49
|
+
.filter(isRecord)
|
|
50
|
+
.find((k) => k.kid === kid &&
|
|
51
|
+
k.kty === "OKP" &&
|
|
52
|
+
k.crv === "Ed25519" &&
|
|
53
|
+
typeof k.x === "string" &&
|
|
54
|
+
(k.alg === undefined || k.alg === "EdDSA" || k.alg === "Ed25519") &&
|
|
55
|
+
(k.use === undefined || k.use === "sig"));
|
|
56
|
+
}
|
|
57
|
+
async function verifiedPayload(token, jwks) {
|
|
58
|
+
if (typeof token !== "string" || token.split(".").length !== 3)
|
|
59
|
+
refuse("malformed", "not a compact JWS");
|
|
60
|
+
let header;
|
|
61
|
+
try {
|
|
62
|
+
header = decodeProtectedHeader(token);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return refuse("malformed", "the header is not a JSON object");
|
|
66
|
+
}
|
|
67
|
+
if (header.alg !== "EdDSA")
|
|
68
|
+
refuse("bad_algorithm", "only EdDSA is accepted");
|
|
69
|
+
const kid = header.kid;
|
|
70
|
+
if (typeof kid !== "string" || kid === "")
|
|
71
|
+
return refuse("missing_kid", "the header has no kid");
|
|
72
|
+
const jwk = ed25519Key(jwks, kid);
|
|
73
|
+
if (!jwk)
|
|
74
|
+
return refuse("unknown_key", `no Ed25519 key has kid ${kid}`);
|
|
75
|
+
let bytes;
|
|
76
|
+
try {
|
|
77
|
+
const key = await importJWK({ kty: "OKP", crv: "Ed25519", x: String(jwk.x) }, "EdDSA");
|
|
78
|
+
({ payload: bytes } = await compactVerify(token, key, {
|
|
79
|
+
algorithms: ["EdDSA"],
|
|
80
|
+
}));
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return refuse("bad_signature");
|
|
84
|
+
}
|
|
85
|
+
let payload;
|
|
86
|
+
try {
|
|
87
|
+
payload = JSON.parse(new TextDecoder().decode(bytes));
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return refuse("malformed", "the payload is not JSON");
|
|
91
|
+
}
|
|
92
|
+
if (!isRecord(payload))
|
|
93
|
+
return refuse("malformed", "the payload is not a JSON object");
|
|
94
|
+
return payload;
|
|
95
|
+
}
|
|
96
|
+
function required(p, claim, is, why = "has the wrong type") {
|
|
97
|
+
const v = p[claim];
|
|
98
|
+
if (v === undefined)
|
|
99
|
+
return refuse("missing_claim", `no ${claim}`);
|
|
100
|
+
if (!is(v))
|
|
101
|
+
return refuse("bad_claim", `${claim} ${why}`);
|
|
102
|
+
return v;
|
|
103
|
+
}
|
|
104
|
+
const isString = (v) => typeof v === "string";
|
|
105
|
+
const isNumber = (v) => typeof v === "number" && Number.isFinite(v);
|
|
106
|
+
const isBoolean = (v) => typeof v === "boolean";
|
|
107
|
+
const isPrn = (v) => isString(v) && PRN.test(v);
|
|
108
|
+
const isOrg = (v) => isString(v) && ORG.test(v);
|
|
109
|
+
const isKind = (v) => isString(v) && KINDS.has(v);
|
|
110
|
+
const isAudience = (v) => isString(v) || isStrings(v);
|
|
111
|
+
const isPrns = (v) => Array.isArray(v) && v.every(isPrn);
|
|
112
|
+
const isAct = (v) => isRecord(v) && isString(v.sub);
|
|
113
|
+
/** The conditional claims a token may carry, and the type each must have when present. */
|
|
114
|
+
const CONDITIONAL = {
|
|
115
|
+
act: isAct,
|
|
116
|
+
email: isString,
|
|
117
|
+
email_verified: isBoolean,
|
|
118
|
+
scope: isString,
|
|
119
|
+
amr: isStrings,
|
|
120
|
+
orgRole: isString,
|
|
121
|
+
client_id: isString,
|
|
122
|
+
azp: isString,
|
|
123
|
+
sid: isString,
|
|
124
|
+
};
|
|
125
|
+
/**
|
|
126
|
+
* Verifies an access token and returns its claims, or throws AccessTokenError. Every refusal is
|
|
127
|
+
* one of ACCESS_TOKEN_ERROR_CODES; fixtures/ecosystem-identity/token_vectors.json is the test.
|
|
128
|
+
*/
|
|
129
|
+
export async function verifyAccessToken(token, opts) {
|
|
130
|
+
const now = opts.now ?? Math.floor(Date.now() / 1000);
|
|
131
|
+
const p = await verifiedPayload(token, opts.jwks);
|
|
132
|
+
const iss = required(p, "iss", isString);
|
|
133
|
+
if (iss !== opts.issuer)
|
|
134
|
+
refuse("wrong_issuer", `iss is ${iss}`);
|
|
135
|
+
const aud = required(p, "aud", isAudience);
|
|
136
|
+
if (Array.isArray(aud) ? !aud.includes(opts.audience) : aud !== opts.audience)
|
|
137
|
+
refuse("wrong_audience");
|
|
138
|
+
const exp = required(p, "exp", isNumber);
|
|
139
|
+
const iat = required(p, "iat", isNumber);
|
|
140
|
+
if (now >= exp + LEEWAY_SECONDS)
|
|
141
|
+
refuse("expired");
|
|
142
|
+
const nbf = p.nbf;
|
|
143
|
+
if (nbf !== undefined && !isNumber(nbf))
|
|
144
|
+
refuse("bad_claim", "nbf");
|
|
145
|
+
if (isNumber(nbf) && nbf > now + LEEWAY_SECONDS)
|
|
146
|
+
refuse("not_yet_valid");
|
|
147
|
+
if (iat > now + LEEWAY_SECONDS)
|
|
148
|
+
refuse("issued_in_future");
|
|
149
|
+
if (exp - iat > MAX_LIFETIME_SECONDS)
|
|
150
|
+
refuse("lifetime_too_long", `lives ${exp - iat} s`);
|
|
151
|
+
const claims = {
|
|
152
|
+
...p,
|
|
153
|
+
iss,
|
|
154
|
+
aud,
|
|
155
|
+
exp,
|
|
156
|
+
iat,
|
|
157
|
+
jti: required(p, "jti", (v) => isString(v) && v !== ""),
|
|
158
|
+
sub: required(p, "sub", isPrn, "is not a prn_ id"),
|
|
159
|
+
principalKind: required(p, "principalKind", isKind, "is not a known kind"),
|
|
160
|
+
org: required(p, "org", isOrg, "is not an org_ id"),
|
|
161
|
+
ent: required(p, "ent", isStrings),
|
|
162
|
+
mayDispatch: required(p, "mayDispatch", isPrns, "holds a value that is not a prn_ id"),
|
|
163
|
+
mayGrantReach: required(p, "mayGrantReach", isBoolean),
|
|
164
|
+
};
|
|
165
|
+
for (const [claim, is] of Object.entries(CONDITIONAL))
|
|
166
|
+
if (p[claim] !== undefined && !is(p[claim]))
|
|
167
|
+
refuse("bad_claim", `${claim} has the wrong type`);
|
|
168
|
+
if (!claims.ent.includes(opts.product))
|
|
169
|
+
refuse("product_not_enabled", `ent does not contain ${opts.product}`);
|
|
170
|
+
return claims;
|
|
171
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -6,7 +6,14 @@
|
|
|
6
6
|
* Import a file by its subpath:
|
|
7
7
|
*
|
|
8
8
|
* import grammar from "@superjackfruitlabs/treaty-ecosystem-identity/id_grammar.json" with { type: "json" };
|
|
9
|
+
*
|
|
10
|
+
* It also exports the suite's one access-token verifier, `verifyAccessToken`, which passes every
|
|
11
|
+
* case in token_vectors.json, and `createJwksCache` to feed it keys.
|
|
9
12
|
*/
|
|
10
13
|
/** Every file in the corpus, by the subpath it is published under. */
|
|
11
|
-
export declare const CORPUS_FILES: readonly ["card_prompt.json", "id_grammar.json", "matrix_gate_events.json", "run_join_key.json", "token_claims.json"];
|
|
14
|
+
export declare const CORPUS_FILES: readonly ["card_prompt.json", "id_grammar.json", "matrix_gate_events.json", "run_join_key.json", "token_claims.json", "token_vectors.json"];
|
|
12
15
|
export type CorpusFile = (typeof CORPUS_FILES)[number];
|
|
16
|
+
export { ACCESS_TOKEN_ERROR_CODES, AccessTokenError, LEEWAY_SECONDS, MAX_LIFETIME_SECONDS, PRINCIPAL_KINDS, verifyAccessToken, } from "./access-token.ts";
|
|
17
|
+
export type { AccessTokenClaims, AccessTokenErrorCode, PrincipalKind, VerifyAccessTokenOptions, } from "./access-token.ts";
|
|
18
|
+
export { createJwksCache } from "./jwks-cache.ts";
|
|
19
|
+
export type { JwksCache, JwksCacheOptions } from "./jwks-cache.ts";
|
package/dist/index.js
CHANGED
|
@@ -6,6 +6,9 @@
|
|
|
6
6
|
* Import a file by its subpath:
|
|
7
7
|
*
|
|
8
8
|
* import grammar from "@superjackfruitlabs/treaty-ecosystem-identity/id_grammar.json" with { type: "json" };
|
|
9
|
+
*
|
|
10
|
+
* It also exports the suite's one access-token verifier, `verifyAccessToken`, which passes every
|
|
11
|
+
* case in token_vectors.json, and `createJwksCache` to feed it keys.
|
|
9
12
|
*/
|
|
10
13
|
/** Every file in the corpus, by the subpath it is published under. */
|
|
11
14
|
export const CORPUS_FILES = [
|
|
@@ -14,4 +17,7 @@ export const CORPUS_FILES = [
|
|
|
14
17
|
"matrix_gate_events.json",
|
|
15
18
|
"run_join_key.json",
|
|
16
19
|
"token_claims.json",
|
|
20
|
+
"token_vectors.json",
|
|
17
21
|
];
|
|
22
|
+
export { ACCESS_TOKEN_ERROR_CODES, AccessTokenError, LEEWAY_SECONDS, MAX_LIFETIME_SECONDS, PRINCIPAL_KINDS, verifyAccessToken, } from "./access-token.js";
|
|
23
|
+
export { createJwksCache } from "./jwks-cache.js";
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A JWKS cache for verifyAccessToken. Stale while revalidate: an old set is served at once and
|
|
3
|
+
* refreshed behind it. A kid the cached set does not hold triggers at most one refetch per
|
|
4
|
+
* `refetchUnknownKidAfterMs` (30 s). Every fetch gives up after `timeoutMs` (3 s), and a failed
|
|
5
|
+
* fetch keeps the last good set; only a cache that never had one throws.
|
|
6
|
+
*/
|
|
7
|
+
export interface JwksCacheOptions {
|
|
8
|
+
url: string;
|
|
9
|
+
fetch?: typeof fetch;
|
|
10
|
+
timeoutMs?: number;
|
|
11
|
+
refetchUnknownKidAfterMs?: number;
|
|
12
|
+
/** How old a set may be before it is refreshed in the background. */
|
|
13
|
+
maxAgeMs?: number;
|
|
14
|
+
/** Milliseconds; defaults to Date.now. */
|
|
15
|
+
now?: () => number;
|
|
16
|
+
}
|
|
17
|
+
export interface JwksCache {
|
|
18
|
+
/** A JWKS for verifyAccessToken's `jwks`, refetched first when it lacks `kid`. */
|
|
19
|
+
getKeys(kid: string | undefined): Promise<{
|
|
20
|
+
keys: unknown[];
|
|
21
|
+
}>;
|
|
22
|
+
}
|
|
23
|
+
export declare function createJwksCache(o: JwksCacheOptions): JwksCache;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A JWKS cache for verifyAccessToken. Stale while revalidate: an old set is served at once and
|
|
3
|
+
* refreshed behind it. A kid the cached set does not hold triggers at most one refetch per
|
|
4
|
+
* `refetchUnknownKidAfterMs` (30 s). Every fetch gives up after `timeoutMs` (3 s), and a failed
|
|
5
|
+
* fetch keeps the last good set; only a cache that never had one throws.
|
|
6
|
+
*/
|
|
7
|
+
const hasKid = (set, kid) => set.keys.some((k) => typeof k === "object" && k !== null && "kid" in k && k.kid === kid);
|
|
8
|
+
export function createJwksCache(o) {
|
|
9
|
+
const doFetch = o.fetch ?? fetch;
|
|
10
|
+
const now = o.now ?? Date.now;
|
|
11
|
+
const timeoutMs = o.timeoutMs ?? 3000;
|
|
12
|
+
const cooldown = o.refetchUnknownKidAfterMs ?? 30_000;
|
|
13
|
+
const maxAge = o.maxAgeMs ?? 600_000;
|
|
14
|
+
let good;
|
|
15
|
+
let inFlight;
|
|
16
|
+
let lastUnknownKid = -Infinity;
|
|
17
|
+
async function load() {
|
|
18
|
+
const abort = new AbortController();
|
|
19
|
+
const timer = setTimeout(() => abort.abort(), timeoutMs);
|
|
20
|
+
let body;
|
|
21
|
+
try {
|
|
22
|
+
const r = await doFetch(o.url, {
|
|
23
|
+
headers: { accept: "application/json" },
|
|
24
|
+
signal: abort.signal,
|
|
25
|
+
});
|
|
26
|
+
if (!r.ok)
|
|
27
|
+
throw new Error(`JWKS ${o.url} answered ${r.status}`);
|
|
28
|
+
body = await r.json();
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
clearTimeout(timer);
|
|
32
|
+
}
|
|
33
|
+
if (typeof body !== "object" ||
|
|
34
|
+
body === null ||
|
|
35
|
+
!("keys" in body) ||
|
|
36
|
+
!Array.isArray(body.keys))
|
|
37
|
+
throw new Error(`JWKS ${o.url} is not a key set`);
|
|
38
|
+
good = { set: { keys: body.keys }, at: now() };
|
|
39
|
+
}
|
|
40
|
+
/** One fetch at a time. A failure is thrown only when there is no set to fall back on. */
|
|
41
|
+
function refresh() {
|
|
42
|
+
inFlight ??= load()
|
|
43
|
+
.catch((e) => {
|
|
44
|
+
if (!good)
|
|
45
|
+
throw e;
|
|
46
|
+
})
|
|
47
|
+
.finally(() => {
|
|
48
|
+
inFlight = undefined;
|
|
49
|
+
});
|
|
50
|
+
return inFlight;
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
async getKeys(kid) {
|
|
54
|
+
if (!good)
|
|
55
|
+
await refresh();
|
|
56
|
+
else if (now() - good.at > maxAge)
|
|
57
|
+
void refresh().catch(() => undefined);
|
|
58
|
+
if (good &&
|
|
59
|
+
!hasKid(good.set, kid) &&
|
|
60
|
+
now() - lastUnknownKid >= cooldown) {
|
|
61
|
+
lastUnknownKid = now();
|
|
62
|
+
await refresh();
|
|
63
|
+
}
|
|
64
|
+
if (!good)
|
|
65
|
+
throw new Error(`JWKS ${o.url} could not be loaded`);
|
|
66
|
+
return good.set;
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@superjackfruitlabs/treaty-ecosystem-identity",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.15",
|
|
4
4
|
"description": "The identity fixture corpus Super Jackfruit Labs products check their ids, tokens, prompts and chat events against.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -28,5 +28,8 @@
|
|
|
28
28
|
"publishConfig": {
|
|
29
29
|
"access": "public",
|
|
30
30
|
"registry": "https://registry.npmjs.org/"
|
|
31
|
+
},
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"jose": "6.2.12"
|
|
31
34
|
}
|
|
32
35
|
}
|