@nodetool-ai/auth 0.7.0-rc.23 → 0.8.2
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 +48 -0
- package/dist/.nodetool-build-stamp +1 -0
- package/dist/auth-provider.d.ts +16 -10
- package/dist/auth-provider.d.ts.map +1 -1
- package/dist/auth-provider.js +14 -6
- package/dist/auth-provider.js.map +1 -1
- package/dist/file-user-manager.d.ts +0 -1
- package/dist/file-user-manager.d.ts.map +1 -1
- package/dist/file-user-manager.js +28 -8
- package/dist/file-user-manager.js.map +1 -1
- package/dist/index.d.ts +2 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -5
- package/dist/index.js.map +1 -1
- package/dist/json-wire.d.ts +38 -0
- package/dist/json-wire.d.ts.map +1 -0
- package/dist/json-wire.js +36 -0
- package/dist/json-wire.js.map +1 -0
- package/dist/providers/app-session-token-provider.d.ts +80 -0
- package/dist/providers/app-session-token-provider.d.ts.map +1 -0
- package/dist/providers/app-session-token-provider.js +180 -0
- package/dist/providers/app-session-token-provider.js.map +1 -0
- package/dist/providers/delegated-token-provider.d.ts +66 -0
- package/dist/providers/delegated-token-provider.d.ts.map +1 -0
- package/dist/providers/delegated-token-provider.js +136 -0
- package/dist/providers/delegated-token-provider.js.map +1 -0
- package/dist/providers/local-provider.d.ts.map +1 -1
- package/dist/providers/supabase-provider.d.ts +2 -1
- package/dist/providers/supabase-provider.d.ts.map +1 -1
- package/dist/providers/supabase-provider.js +78 -12
- package/dist/providers/supabase-provider.js.map +1 -1
- package/package.json +23 -6
- package/dist/http-auth.d.ts +0 -22
- package/dist/http-auth.d.ts.map +0 -1
- package/dist/http-auth.js +0 -51
- package/dist/http-auth.js.map +0 -1
- package/dist/middleware.d.ts +0 -37
- package/dist/middleware.d.ts.map +0 -1
- package/dist/middleware.js +0 -69
- package/dist/middleware.js.map +0 -1
- package/dist/providers/multi-user-provider.d.ts +0 -16
- package/dist/providers/multi-user-provider.d.ts.map +0 -1
- package/dist/providers/multi-user-provider.js +0 -40
- package/dist/providers/multi-user-provider.js.map +0 -1
- package/dist/providers/static-token-provider.d.ts +0 -23
- package/dist/providers/static-token-provider.d.ts.map +0 -1
- package/dist/providers/static-token-provider.js +0 -57
- package/dist/providers/static-token-provider.js.map +0 -1
- package/dist/user-manager.d.ts +0 -23
- package/dist/user-manager.d.ts.map +0 -1
- package/dist/user-manager.js +0 -30
- package/dist/user-manager.js.map +0 -1
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* App session tokens: short-lived, HMAC-signed bearer tokens that let an
|
|
3
|
+
* anonymous visitor run one deployed mini app, and nothing else.
|
|
4
|
+
*
|
|
5
|
+
* A deployed app is served from a hidden URL with no login (see
|
|
6
|
+
* `isAppDeploymentEnabled` in `@nodetool-ai/protocol`). Its runs execute on the
|
|
7
|
+
* owner's account — their pinned graphs, their provider keys, their spend
|
|
8
|
+
* budget — so the visitor needs an identity, and it cannot be the owner's own.
|
|
9
|
+
* This token carries the owner's user id *and* the application it is confined
|
|
10
|
+
* to, and every consumer is required to read the second field: the token
|
|
11
|
+
* answers "who pays" and "for what" together, so a caller cannot accidentally
|
|
12
|
+
* treat it as an ordinary session.
|
|
13
|
+
*
|
|
14
|
+
* That confinement is the whole point, so it is structural rather than a
|
|
15
|
+
* claim to check later. `TokenType.APP_SESSION` is a distinct type with no
|
|
16
|
+
* overlap with `USER`, and `AuthResult.applicationId` is only ever set by this
|
|
17
|
+
* provider — a host that forgets to narrow on the type still cannot mistake
|
|
18
|
+
* one for a full session, because the field it must consult is present.
|
|
19
|
+
*
|
|
20
|
+
* Like delegated tokens, the signature is the whole state: no token table, no
|
|
21
|
+
* cleanup job. Rotating the signing key invalidates every outstanding token;
|
|
22
|
+
* revoking the deployment stops new ones from minting, and the ones already
|
|
23
|
+
* out die at their expiry.
|
|
24
|
+
*/
|
|
25
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
26
|
+
import { AuthProvider, TokenType } from "../auth-provider.js";
|
|
27
|
+
import { isFiniteNumber, isJsonObject, isNonEmptyString } from "../json-wire.js";
|
|
28
|
+
/**
|
|
29
|
+
* What marks a token as this provider's. A token without it is somebody
|
|
30
|
+
* else's — `verifyToken` says so without spending a comparison, and a chained
|
|
31
|
+
* caller falls through to the next provider.
|
|
32
|
+
*/
|
|
33
|
+
export const APP_SESSION_TOKEN_PREFIX = "nda_";
|
|
34
|
+
/** Payload version, so a future field is a version bump rather than a guess. */
|
|
35
|
+
const PAYLOAD_VERSION = 1;
|
|
36
|
+
function base64url(value) {
|
|
37
|
+
return value.toString("base64url");
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The token's signature: HMAC-SHA256 over the encoded payload.
|
|
41
|
+
*
|
|
42
|
+
* CodeQL's `js/insufficient-password-hash` reports this line, having tracked
|
|
43
|
+
* the `?api_key=` query parameter that carries a presented token into
|
|
44
|
+
* `update()`. It is a false positive, and the premise it rests on is pinned by
|
|
45
|
+
* test rather than argued in review (see `app-session-token-provider.test.ts`
|
|
46
|
+
* § "what makes the fast hash safe here"):
|
|
47
|
+
*
|
|
48
|
+
* - Nothing here is a password and nothing is stored. `material` is the
|
|
49
|
+
* token's *own* payload — base64url JSON that anyone holding the token can
|
|
50
|
+
* already read — and the digest is recomputed and compared on the spot, in
|
|
51
|
+
* constant time. There is no hash at rest for an attacker to crack.
|
|
52
|
+
* - Unforgeability rests on the key, not on the hash being slow. The server
|
|
53
|
+
* passes a 32-byte PBKDF2-derived key (`deriveKey(getMasterKey(), …)`), so
|
|
54
|
+
* forging a signature means guessing 256 bits; a slow KDF would add nothing
|
|
55
|
+
* and would break verification, which must be keyed and deterministic.
|
|
56
|
+
*
|
|
57
|
+
* HMAC-SHA256 is the right primitive for a MAC — it is what JWT's HS256 is,
|
|
58
|
+
* and what this package's delegated tokens already use.
|
|
59
|
+
*/
|
|
60
|
+
function sign(key, material) {
|
|
61
|
+
return base64url(createHmac("sha256", key).update(material).digest());
|
|
62
|
+
}
|
|
63
|
+
/** Whether a token claims to be an app session token at all. */
|
|
64
|
+
export function isAppSessionToken(token) {
|
|
65
|
+
return token.startsWith(APP_SESSION_TOKEN_PREFIX);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Mint a session token for one deployed app.
|
|
69
|
+
*
|
|
70
|
+
* @param key - HMAC signing key. The same key must reach the provider that
|
|
71
|
+
* verifies the token.
|
|
72
|
+
* @param scope - The app owner, the application, and the release the visitor
|
|
73
|
+
* loaded.
|
|
74
|
+
* @param ttlSeconds - Lifetime from now. A zero or negative value mints an
|
|
75
|
+
* already-expired token, which is how the expiry path is tested.
|
|
76
|
+
*/
|
|
77
|
+
export function mintAppSessionToken(key, scope, ttlSeconds, now = Date.now) {
|
|
78
|
+
if (!isNonEmptyString(scope.userId)) {
|
|
79
|
+
throw new Error("An app session token needs a user id");
|
|
80
|
+
}
|
|
81
|
+
if (!isNonEmptyString(scope.applicationId)) {
|
|
82
|
+
throw new Error("An app session token needs an application id");
|
|
83
|
+
}
|
|
84
|
+
if (!Number.isInteger(scope.version)) {
|
|
85
|
+
throw new Error("An app session token needs a released version");
|
|
86
|
+
}
|
|
87
|
+
const expiresAtMs = now() + Math.round(ttlSeconds * 1000);
|
|
88
|
+
const payload = {
|
|
89
|
+
v: PAYLOAD_VERSION,
|
|
90
|
+
u: scope.userId,
|
|
91
|
+
a: scope.applicationId,
|
|
92
|
+
r: scope.version,
|
|
93
|
+
e: Math.floor(expiresAtMs / 1000)
|
|
94
|
+
};
|
|
95
|
+
const encoded = base64url(Buffer.from(JSON.stringify(payload), "utf-8"));
|
|
96
|
+
const material = `${APP_SESSION_TOKEN_PREFIX}${encoded}`;
|
|
97
|
+
return {
|
|
98
|
+
token: `${material}.${sign(key, material)}`,
|
|
99
|
+
expiresAt: new Date(payload.e * 1000).toISOString()
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/** Read a payload back, or null when it is not the shape one was written in. */
|
|
103
|
+
function decodePayload(encoded) {
|
|
104
|
+
let parsed;
|
|
105
|
+
try {
|
|
106
|
+
parsed = JSON.parse(Buffer.from(encoded, "base64url").toString("utf-8"));
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
// A payload that is not base64url-encoded JSON is not one this minted.
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
if (!isJsonObject(parsed))
|
|
113
|
+
return null;
|
|
114
|
+
const { v, u, a, r, e } = parsed;
|
|
115
|
+
if (v !== PAYLOAD_VERSION)
|
|
116
|
+
return null;
|
|
117
|
+
if (!isNonEmptyString(u))
|
|
118
|
+
return null;
|
|
119
|
+
if (!isNonEmptyString(a))
|
|
120
|
+
return null;
|
|
121
|
+
if (!isFiniteNumber(r))
|
|
122
|
+
return null;
|
|
123
|
+
if (!isFiniteNumber(e))
|
|
124
|
+
return null;
|
|
125
|
+
return { v, u, a, r, e };
|
|
126
|
+
}
|
|
127
|
+
function isKeyAccessor(key) {
|
|
128
|
+
return typeof key === "function";
|
|
129
|
+
}
|
|
130
|
+
export class AppSessionTokenProvider extends AuthProvider {
|
|
131
|
+
key;
|
|
132
|
+
now;
|
|
133
|
+
constructor(key, options = {}) {
|
|
134
|
+
super();
|
|
135
|
+
this.key = key;
|
|
136
|
+
this.now = options.now ?? Date.now;
|
|
137
|
+
}
|
|
138
|
+
signingKey() {
|
|
139
|
+
return isKeyAccessor(this.key) ? this.key() : this.key;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Verify an app session token. Every failure — wrong prefix, malformed,
|
|
143
|
+
* tampered, expired — is a not-ok result rather than a throw, so a chained
|
|
144
|
+
* caller can fall through to the next provider on any of them.
|
|
145
|
+
*/
|
|
146
|
+
async verifyToken(token) {
|
|
147
|
+
if (!isNonEmptyString(token) || !isAppSessionToken(token)) {
|
|
148
|
+
return { ok: false, error: "Not an app session token" };
|
|
149
|
+
}
|
|
150
|
+
const separator = token.lastIndexOf(".");
|
|
151
|
+
if (separator < 0) {
|
|
152
|
+
return { ok: false, error: "Malformed app session token" };
|
|
153
|
+
}
|
|
154
|
+
const material = token.slice(0, separator);
|
|
155
|
+
const presented = Buffer.from(token.slice(separator + 1), "utf-8");
|
|
156
|
+
const expected = Buffer.from(sign(this.signingKey(), material), "utf-8");
|
|
157
|
+
if (presented.length !== expected.length ||
|
|
158
|
+
!timingSafeEqual(presented, expected)) {
|
|
159
|
+
return { ok: false, error: "Invalid app session token signature" };
|
|
160
|
+
}
|
|
161
|
+
const payload = decodePayload(material.slice(APP_SESSION_TOKEN_PREFIX.length));
|
|
162
|
+
if (!payload) {
|
|
163
|
+
return { ok: false, error: "Malformed app session token" };
|
|
164
|
+
}
|
|
165
|
+
if (payload.e * 1000 <= this.now()) {
|
|
166
|
+
return { ok: false, error: "App session token expired" };
|
|
167
|
+
}
|
|
168
|
+
return {
|
|
169
|
+
ok: true,
|
|
170
|
+
userId: payload.u,
|
|
171
|
+
tokenType: TokenType.APP_SESSION,
|
|
172
|
+
applicationId: payload.a,
|
|
173
|
+
applicationVersion: payload.r
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
clearCaches() {
|
|
177
|
+
// Stateless: the signature is the whole state.
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
//# sourceMappingURL=app-session-token-provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app-session-token-provider.js","sourceRoot":"","sources":["../../src/providers/app-session-token-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE1D,OAAO,EAAE,YAAY,EAAc,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAC1E,OAAO,EACL,cAAc,EACd,YAAY,EACZ,gBAAgB,EACjB,MAAM,iBAAiB,CAAC;AAEzB;;;;GAIG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,MAAM,CAAC;AAE/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K,CAAC,KAAK,CAAC,SAAS,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;QACnE,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAC;QACzE,IACE,SAAS,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM;YACpC,CAAC,eAAe,CAAC,SAAS,EAAE,QAAQ,CAAC,EACrC,CAAC;YACD,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,qCAAqC,EAAE,CAAC;QACrE,CAAC;QAED,MAAM,OAAO,GAAG,aAAa,CAC3B,QAAQ,CAAC,KAAK,CAAC,wBAAwB,CAAC,MAAM,CAAC,CAChD,CAAC;QACF,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,6BAA6B,EAAE,CAAC;QAC7D,CAAC;QACD,IAAI,OAAO,CAAC,CAAC,GAAG,IAAI,IAAI,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;YACnC,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,2BAA2B,EAAE,CAAC;QAC3D,CAAC;QAED,OAAO;YACL,EAAE,EAAE,IAAI;YACR,MAAM,EAAE,OAAO,CAAC,CAAC;YACjB,SAAS,EAAE,SAAS,CAAC,WAAW;YAChC,aAAa,EAAE,OAAO,CAAC,CAAC;YACxB,kBAAkB,EAAE,OAAO,CAAC,CAAC;SAC9B,CAAC;IACJ,CAAC;IAED,WAAW;QACT,+CAA+C;IACjD,CAAC;CACF"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Delegated tokens: short-lived, HMAC-signed bearer tokens that authenticate
|
|
3
|
+
* as one NodeTool user.
|
|
4
|
+
*
|
|
5
|
+
* A messaging bridge (Telegram, later Discord) holds one service token that
|
|
6
|
+
* identifies the integration, never a user credential. Per connection it asks
|
|
7
|
+
* the server to mint a delegated token for the user its external account is
|
|
8
|
+
* linked to, and that token is what every request runs on — so tenant
|
|
9
|
+
* isolation stays the server's, enforced by the same rules a browser session
|
|
10
|
+
* gets.
|
|
11
|
+
*
|
|
12
|
+
* The signature is the whole state: there is no token table and no cleanup
|
|
13
|
+
* job. Unlinking stops new tokens from minting and outstanding ones die at
|
|
14
|
+
* their expiry; rotating the signing key kills them immediately.
|
|
15
|
+
*
|
|
16
|
+
* The key itself is the caller's business. Nothing here reads the master key —
|
|
17
|
+
* `@nodetool-ai/security` is not a dependency of this package — so the wiring
|
|
18
|
+
* site (the server) derives a key and passes it in.
|
|
19
|
+
*/
|
|
20
|
+
import { AuthProvider, AuthResult } from "../auth-provider.js";
|
|
21
|
+
/**
|
|
22
|
+
* What marks a token as this provider's. A token without it is somebody
|
|
23
|
+
* else's — `verifyToken` says so without spending a comparison, and a chained
|
|
24
|
+
* caller falls through to the next provider.
|
|
25
|
+
*/
|
|
26
|
+
export declare const DELEGATED_TOKEN_PREFIX = "ndt_";
|
|
27
|
+
export interface MintedDelegatedToken {
|
|
28
|
+
token: string;
|
|
29
|
+
/** Expiry as an ISO-8601 string, the shape the integration routes return. */
|
|
30
|
+
expiresAt: string;
|
|
31
|
+
}
|
|
32
|
+
/** Whether a token claims to be a delegated token at all. */
|
|
33
|
+
export declare function isDelegatedToken(token: string): boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Mint a delegated token for a user.
|
|
36
|
+
*
|
|
37
|
+
* @param key - HMAC signing key. The same key must reach the provider that
|
|
38
|
+
* verifies the token.
|
|
39
|
+
* @param userId - The NodeTool user the token authenticates as.
|
|
40
|
+
* @param ttlSeconds - Lifetime from now. A zero or negative value mints an
|
|
41
|
+
* already-expired token, which is how the expiry path is tested.
|
|
42
|
+
*/
|
|
43
|
+
export declare function mintDelegatedToken(key: Buffer | string, userId: string, ttlSeconds: number, now?: () => number): MintedDelegatedToken;
|
|
44
|
+
export interface DelegatedTokenProviderOptions {
|
|
45
|
+
/** Injected clock, so expiry is testable without waiting an hour. */
|
|
46
|
+
now?: () => number;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The signing key, or a function returning it. The accessor form lets a host
|
|
50
|
+
* defer key derivation until the first token actually arrives.
|
|
51
|
+
*/
|
|
52
|
+
export type DelegatedSigningKey = Buffer | string | (() => Buffer | string);
|
|
53
|
+
export declare class DelegatedTokenProvider extends AuthProvider {
|
|
54
|
+
private readonly key;
|
|
55
|
+
private readonly now;
|
|
56
|
+
constructor(key: DelegatedSigningKey, options?: DelegatedTokenProviderOptions);
|
|
57
|
+
private signingKey;
|
|
58
|
+
/**
|
|
59
|
+
* Verify a delegated token. Every failure — wrong prefix, malformed,
|
|
60
|
+
* tampered, expired — is a not-ok result rather than a throw, so a chained
|
|
61
|
+
* caller can fall through to the next provider on any of them.
|
|
62
|
+
*/
|
|
63
|
+
verifyToken(token: string): Promise<AuthResult>;
|
|
64
|
+
clearCaches(): void;
|
|
65
|
+
}
|
|
66
|
+
//# sourceMappingURL=delegated-token-provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"delegated-token-provider.d.ts","sourceRoot":"","sources":["../../src/providers/delegated-token-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAIH,OAAO,EAAE,YAAY,EAAE,UAAU,EAAa,MAAM,qBAAqB,CAAC;AAO1E;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,SAAS,CAAC;AAY7C,MAAM,WAAW,oBAAoB;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,6EAA6E;IAC7E,SAAS,EAAE,MAAM,CAAC;CACnB;AAUD,6DAA6D;AAC7D,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEvD;AAED;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,MAAM,GAAG,MAAM,EACpB,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,MAAM,EAClB,GAAG,GAAE,MAAM,MAAiB,GAC3B,oBAAoB,CAgBtB;AAmBD,MAAM,WAAW,6BAA6B;IAC5C,qEAAqE;IACrE,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB;AAED;;;GAGG;AACH,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,MAAM,GAAG,CAAC,MAAM,MAAM,GAAG,MAAM,CAAC,CAAC;AAS5E,qBAAa,sBAAuB,SAAQ,YAAY;IACtD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAsB;IAC1C,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAe;IAEnC,YACE,GAAG,EAAE,mBAAmB,EACxB,OAAO,GAAE,6BAAkC,EAK5C;IAED,OAAO,CAAC,UAAU;IAIlB;;;;OAIG;IACG,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CA4BpD;IAED,WAAW,IAAI,IAAI,CAElB;CACF"}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Delegated tokens: short-lived, HMAC-signed bearer tokens that authenticate
|
|
3
|
+
* as one NodeTool user.
|
|
4
|
+
*
|
|
5
|
+
* A messaging bridge (Telegram, later Discord) holds one service token that
|
|
6
|
+
* identifies the integration, never a user credential. Per connection it asks
|
|
7
|
+
* the server to mint a delegated token for the user its external account is
|
|
8
|
+
* linked to, and that token is what every request runs on — so tenant
|
|
9
|
+
* isolation stays the server's, enforced by the same rules a browser session
|
|
10
|
+
* gets.
|
|
11
|
+
*
|
|
12
|
+
* The signature is the whole state: there is no token table and no cleanup
|
|
13
|
+
* job. Unlinking stops new tokens from minting and outstanding ones die at
|
|
14
|
+
* their expiry; rotating the signing key kills them immediately.
|
|
15
|
+
*
|
|
16
|
+
* The key itself is the caller's business. Nothing here reads the master key —
|
|
17
|
+
* `@nodetool-ai/security` is not a dependency of this package — so the wiring
|
|
18
|
+
* site (the server) derives a key and passes it in.
|
|
19
|
+
*/
|
|
20
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
21
|
+
import { AuthProvider, TokenType } from "../auth-provider.js";
|
|
22
|
+
import { isFiniteNumber, isJsonObject, isNonEmptyString } from "../json-wire.js";
|
|
23
|
+
/**
|
|
24
|
+
* What marks a token as this provider's. A token without it is somebody
|
|
25
|
+
* else's — `verifyToken` says so without spending a comparison, and a chained
|
|
26
|
+
* caller falls through to the next provider.
|
|
27
|
+
*/
|
|
28
|
+
export const DELEGATED_TOKEN_PREFIX = "ndt_";
|
|
29
|
+
/** Payload version, so a future field is a version bump rather than a guess. */
|
|
30
|
+
const PAYLOAD_VERSION = 1;
|
|
31
|
+
function base64url(value) {
|
|
32
|
+
return value.toString("base64url");
|
|
33
|
+
}
|
|
34
|
+
function sign(key, material) {
|
|
35
|
+
return base64url(createHmac("sha256", key).update(material).digest());
|
|
36
|
+
}
|
|
37
|
+
/** Whether a token claims to be a delegated token at all. */
|
|
38
|
+
export function isDelegatedToken(token) {
|
|
39
|
+
return token.startsWith(DELEGATED_TOKEN_PREFIX);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Mint a delegated token for a user.
|
|
43
|
+
*
|
|
44
|
+
* @param key - HMAC signing key. The same key must reach the provider that
|
|
45
|
+
* verifies the token.
|
|
46
|
+
* @param userId - The NodeTool user the token authenticates as.
|
|
47
|
+
* @param ttlSeconds - Lifetime from now. A zero or negative value mints an
|
|
48
|
+
* already-expired token, which is how the expiry path is tested.
|
|
49
|
+
*/
|
|
50
|
+
export function mintDelegatedToken(key, userId, ttlSeconds, now = Date.now) {
|
|
51
|
+
if (!isNonEmptyString(userId)) {
|
|
52
|
+
throw new Error("A delegated token needs a user id");
|
|
53
|
+
}
|
|
54
|
+
const expiresAtMs = now() + Math.round(ttlSeconds * 1000);
|
|
55
|
+
const payload = {
|
|
56
|
+
v: PAYLOAD_VERSION,
|
|
57
|
+
u: userId,
|
|
58
|
+
e: Math.floor(expiresAtMs / 1000)
|
|
59
|
+
};
|
|
60
|
+
const encoded = base64url(Buffer.from(JSON.stringify(payload), "utf-8"));
|
|
61
|
+
const material = `${DELEGATED_TOKEN_PREFIX}${encoded}`;
|
|
62
|
+
return {
|
|
63
|
+
token: `${material}.${sign(key, material)}`,
|
|
64
|
+
expiresAt: new Date(payload.e * 1000).toISOString()
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
/** Read a payload back, or null when it is not the shape one was written in. */
|
|
68
|
+
function decodePayload(encoded) {
|
|
69
|
+
let parsed;
|
|
70
|
+
try {
|
|
71
|
+
parsed = JSON.parse(Buffer.from(encoded, "base64url").toString("utf-8"));
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// A payload that is not base64url-encoded JSON is not one this minted.
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
if (!isJsonObject(parsed))
|
|
78
|
+
return null;
|
|
79
|
+
const { v, u, e } = parsed;
|
|
80
|
+
if (v !== PAYLOAD_VERSION)
|
|
81
|
+
return null;
|
|
82
|
+
if (!isNonEmptyString(u))
|
|
83
|
+
return null;
|
|
84
|
+
if (!isFiniteNumber(e))
|
|
85
|
+
return null;
|
|
86
|
+
return { v, u, e };
|
|
87
|
+
}
|
|
88
|
+
/** Whether a key was supplied as an accessor rather than as the key itself. */
|
|
89
|
+
function isKeyAccessor(key) {
|
|
90
|
+
return typeof key === "function";
|
|
91
|
+
}
|
|
92
|
+
export class DelegatedTokenProvider extends AuthProvider {
|
|
93
|
+
key;
|
|
94
|
+
now;
|
|
95
|
+
constructor(key, options = {}) {
|
|
96
|
+
super();
|
|
97
|
+
this.key = key;
|
|
98
|
+
this.now = options.now ?? Date.now;
|
|
99
|
+
}
|
|
100
|
+
signingKey() {
|
|
101
|
+
return isKeyAccessor(this.key) ? this.key() : this.key;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Verify a delegated token. Every failure — wrong prefix, malformed,
|
|
105
|
+
* tampered, expired — is a not-ok result rather than a throw, so a chained
|
|
106
|
+
* caller can fall through to the next provider on any of them.
|
|
107
|
+
*/
|
|
108
|
+
async verifyToken(token) {
|
|
109
|
+
if (!isNonEmptyString(token) || !isDelegatedToken(token)) {
|
|
110
|
+
return { ok: false, error: "Not a delegated token" };
|
|
111
|
+
}
|
|
112
|
+
const separator = token.lastIndexOf(".");
|
|
113
|
+
if (separator < 0) {
|
|
114
|
+
return { ok: false, error: "Malformed delegated token" };
|
|
115
|
+
}
|
|
116
|
+
const material = token.slice(0, separator);
|
|
117
|
+
const presented = Buffer.from(token.slice(separator + 1), "utf-8");
|
|
118
|
+
const expected = Buffer.from(sign(this.signingKey(), material), "utf-8");
|
|
119
|
+
if (presented.length !== expected.length ||
|
|
120
|
+
!timingSafeEqual(presented, expected)) {
|
|
121
|
+
return { ok: false, error: "Invalid delegated token signature" };
|
|
122
|
+
}
|
|
123
|
+
const payload = decodePayload(material.slice(DELEGATED_TOKEN_PREFIX.length));
|
|
124
|
+
if (!payload) {
|
|
125
|
+
return { ok: false, error: "Malformed delegated token" };
|
|
126
|
+
}
|
|
127
|
+
if (payload.e * 1000 <= this.now()) {
|
|
128
|
+
return { ok: false, error: "Delegated token expired" };
|
|
129
|
+
}
|
|
130
|
+
return { ok: true, userId: payload.u, tokenType: TokenType.USER };
|
|
131
|
+
}
|
|
132
|
+
clearCaches() {
|
|
133
|
+
// Stateless: the signature is the whole state.
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
//# sourceMappingURL=delegated-token-provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"delegated-token-provider.js","sourceRoot":"","sources":["../../src/providers/delegated-token-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAE1D,OAAO,EAAE,YAAY,EAAc,SAAS,EAAE,MAAM,qBAAqB,CAAC;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C,QAAQ,CAAC,KAAK,CAAC,sBAAsB,CAAC,MAAM,CAAC,CAAC,CAAC;QAC7E,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,2BAA2B,EAAE,CAAC;QAC3D,CAAC;QACD,IAAI,OAAO,CAAC,CAAC,GAAG,IAAI,IAAI,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC;YACnC,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,yBAAyB,EAAE,CAAC;QACzD,CAAC;QAED,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,EAAE,SAAS,EAAE,SAAS,CAAC,IAAI,EAAE,CAAC;IACpE,CAAC;IAED,WAAW;QACT,+CAA+C;IACjD,CAAC;CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-provider.d.ts","sourceRoot":"","sources":["../../src/providers/local-provider.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,YAAY,EAAE,UAAU,EAAa,MAAM,qBAAqB,CAAC;AAE1E;;;;;GAKG;AACH,qBAAa,iBAAkB,SAAQ,YAAY;IACjD,MAAM,EAAE,MAAM,CAAO;IAEf,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"local-provider.d.ts","sourceRoot":"","sources":["../../src/providers/local-provider.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,YAAY,EAAE,UAAU,EAAa,MAAM,qBAAqB,CAAC;AAE1E;;;;;GAKG;AACH,qBAAa,iBAAkB,SAAQ,YAAY;IACjD,MAAM,EAAE,MAAM,CAAO;IAEf,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAErD;CACF"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Supabase JWT authentication provider — T-SEC-4.
|
|
3
3
|
*
|
|
4
|
-
* Validates Supabase JWT tokens
|
|
4
|
+
* Validates Supabase JWT tokens against the GoTrue REST endpoint
|
|
5
|
+
* (`GET /auth/v1/user`) with a plain `fetch` call — no supabase-js.
|
|
5
6
|
* Uses an LRU token cache with TTL to avoid repeated API calls.
|
|
6
7
|
*
|
|
7
8
|
* Ported from Python: src/nodetool/security/providers/supabase.py
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"supabase-provider.d.ts","sourceRoot":"","sources":["../../src/providers/supabase-provider.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"supabase-provider.d.ts","sourceRoot":"","sources":["../../src/providers/supabase-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,EAAE,YAAY,EAAE,UAAU,EAAa,MAAM,qBAAqB,CAAC;AA+F1E,MAAM,WAAW,2BAA2B;IAC1C,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,sEAAsE;IACtE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sDAAsD;IACtD,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,qBAAa,oBAAqB,SAAQ,YAAY;IACpD,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,OAAO,CAAmC;IAElD;;;;OAIG;IACH,OAAO,CAAC,MAAM,CAAuC;IAErD,YAAY,OAAO,EAAE,2BAA2B,EAM/C;IAED,OAAO,CAAC,UAAU;IAOlB,OAAO,CAAC,aAAa;IAIrB,OAAO,CAAC,cAAc;IAsBtB,OAAO,CAAC,UAAU;IA0BZ,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAsCpD;IAEQ,WAAW,IAAI,IAAI,CAG3B;CACF"}
|
|
@@ -1,14 +1,71 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Supabase JWT authentication provider — T-SEC-4.
|
|
3
3
|
*
|
|
4
|
-
* Validates Supabase JWT tokens
|
|
4
|
+
* Validates Supabase JWT tokens against the GoTrue REST endpoint
|
|
5
|
+
* (`GET /auth/v1/user`) with a plain `fetch` call — no supabase-js.
|
|
5
6
|
* Uses an LRU token cache with TTL to avoid repeated API calls.
|
|
6
7
|
*
|
|
7
8
|
* Ported from Python: src/nodetool/security/providers/supabase.py
|
|
8
9
|
*/
|
|
9
10
|
import { createHash } from "node:crypto";
|
|
10
|
-
import { createClient } from "@supabase/supabase-js";
|
|
11
11
|
import { AuthProvider, TokenType } from "../auth-provider.js";
|
|
12
|
+
import { isJsonObject, readIdentifier, readString } from "../json-wire.js";
|
|
13
|
+
/** The spellings GoTrue uses for an error message, most specific first. */
|
|
14
|
+
const GOTRUE_ERROR_FIELDS = ["msg", "message", "error_description", "error"];
|
|
15
|
+
/** Extract a human-readable message from a decoded GoTrue error body. */
|
|
16
|
+
function readGoTrueErrorMessage(body, status) {
|
|
17
|
+
if (body !== null) {
|
|
18
|
+
for (const field of GOTRUE_ERROR_FIELDS) {
|
|
19
|
+
const message = readString(body, field);
|
|
20
|
+
if (message !== undefined)
|
|
21
|
+
return message;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return `Supabase auth request failed with status ${status}`;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* fetch-backed GoTrue client covering exactly the surface we use:
|
|
28
|
+
* `GET {supabaseUrl}/auth/v1/user` with the token as Bearer auth.
|
|
29
|
+
*/
|
|
30
|
+
function createGoTrueClient(supabaseUrl, supabaseKey) {
|
|
31
|
+
let base = supabaseUrl;
|
|
32
|
+
while (base.endsWith("/"))
|
|
33
|
+
base = base.slice(0, -1);
|
|
34
|
+
return {
|
|
35
|
+
auth: {
|
|
36
|
+
async getUser(token) {
|
|
37
|
+
const response = await fetch(`${base}/auth/v1/user`, {
|
|
38
|
+
method: "GET",
|
|
39
|
+
headers: {
|
|
40
|
+
apikey: supabaseKey,
|
|
41
|
+
Authorization: `Bearer ${token}`
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
// The body is untrusted network JSON. Decode it to the wire shape
|
|
45
|
+
// here, at the boundary, so no read below works on `unknown`.
|
|
46
|
+
let body = null;
|
|
47
|
+
try {
|
|
48
|
+
const decoded = await response.json();
|
|
49
|
+
body = isJsonObject(decoded) ? decoded : null;
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
// Non-JSON body (e.g. empty 5xx) — handled below via status.
|
|
53
|
+
}
|
|
54
|
+
if (!response.ok) {
|
|
55
|
+
return {
|
|
56
|
+
data: { user: null },
|
|
57
|
+
error: {
|
|
58
|
+
message: readGoTrueErrorMessage(body, response.status)
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const id = body === null ? undefined : readIdentifier(body, "id");
|
|
63
|
+
const user = id === undefined ? null : { id };
|
|
64
|
+
return { data: { user }, error: null };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
12
69
|
/**
|
|
13
70
|
* Auth provider that validates Supabase JWT tokens.
|
|
14
71
|
*/
|
|
@@ -31,18 +88,19 @@ export class SupabaseAuthProvider extends AuthProvider {
|
|
|
31
88
|
this.cacheTtl = Math.max(options.cacheTtl ?? 60, 0);
|
|
32
89
|
this.cacheMax = Math.max(options.cacheMax ?? 2000, 0);
|
|
33
90
|
}
|
|
34
|
-
// ── Client initialisation ────────────────────────────────────────────
|
|
35
91
|
_getClient() {
|
|
36
92
|
if (!this._client) {
|
|
37
|
-
this._client =
|
|
93
|
+
this._client = createGoTrueClient(this.supabaseUrl, this.supabaseKey);
|
|
38
94
|
}
|
|
39
95
|
return this._client;
|
|
40
96
|
}
|
|
41
|
-
// ── Cache helpers ────────────────────────────────────────────────────
|
|
42
97
|
_makeCacheKey(token) {
|
|
43
98
|
return createHash("sha256").update(token).digest("hex");
|
|
44
99
|
}
|
|
45
100
|
_getCachedUser(token) {
|
|
101
|
+
// Stryker disable next-line ConditionalExpression,EqualityOperator: redundant
|
|
102
|
+
// with _cacheUser's matching ttl gate — entries are never stored when
|
|
103
|
+
// cacheTtl<=0, so this guarded cache read is unreachable (equivalent).
|
|
46
104
|
if (this.cacheTtl <= 0)
|
|
47
105
|
return null;
|
|
48
106
|
const key = this._makeCacheKey(token);
|
|
@@ -51,7 +109,6 @@ export class SupabaseAuthProvider extends AuthProvider {
|
|
|
51
109
|
return null;
|
|
52
110
|
const [userId, expiresAt] = entry;
|
|
53
111
|
if (performance.now() >= expiresAt) {
|
|
54
|
-
// Expired
|
|
55
112
|
this._cache.delete(key);
|
|
56
113
|
return null;
|
|
57
114
|
}
|
|
@@ -61,6 +118,10 @@ export class SupabaseAuthProvider extends AuthProvider {
|
|
|
61
118
|
return userId;
|
|
62
119
|
}
|
|
63
120
|
_cacheUser(token, userId) {
|
|
121
|
+
// Stryker disable next-line all: redundant fast-path. cacheTtl<=0 entries are
|
|
122
|
+
// never read (gated in _getCachedUser), and cacheMax<=0 stores are immediately
|
|
123
|
+
// removed by the size>cacheMax eviction below, so every mutant here leaves the
|
|
124
|
+
// observable cache state unchanged (equivalent).
|
|
64
125
|
if (this.cacheTtl <= 0 || this.cacheMax <= 0)
|
|
65
126
|
return;
|
|
66
127
|
const key = this._makeCacheKey(token);
|
|
@@ -71,17 +132,18 @@ export class SupabaseAuthProvider extends AuthProvider {
|
|
|
71
132
|
// Evict oldest (first key) when over capacity
|
|
72
133
|
if (this._cache.size > this.cacheMax) {
|
|
73
134
|
const oldest = this._cache.keys().next().value;
|
|
135
|
+
// Stryker disable next-line ConditionalExpression: eviction only runs when
|
|
136
|
+
// size>cacheMax, so the map is non-empty and oldest is always defined here
|
|
137
|
+
// (the undefined guard can never be false — equivalent).
|
|
74
138
|
if (oldest !== undefined) {
|
|
75
139
|
this._cache.delete(oldest);
|
|
76
140
|
}
|
|
77
141
|
}
|
|
78
142
|
}
|
|
79
|
-
// ── AuthProvider implementation ──────────────────────────────────────
|
|
80
143
|
async verifyToken(token) {
|
|
81
144
|
if (!token) {
|
|
82
145
|
return { ok: false, error: "Missing Supabase token" };
|
|
83
146
|
}
|
|
84
|
-
// Check cache first
|
|
85
147
|
const cachedUserId = this._getCachedUser(token);
|
|
86
148
|
if (cachedUserId) {
|
|
87
149
|
return { ok: true, userId: cachedUserId, tokenType: TokenType.USER };
|
|
@@ -90,10 +152,14 @@ export class SupabaseAuthProvider extends AuthProvider {
|
|
|
90
152
|
try {
|
|
91
153
|
const { data, error } = await client.auth.getUser(token);
|
|
92
154
|
if (error) {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
155
|
+
// `error` is truthy here, so it cannot be null. Its declared shape is
|
|
156
|
+
// `{ message }`, but this client is injectable and the tests feed it
|
|
157
|
+
// strings, numbers and message-less objects, so render whatever
|
|
158
|
+
// arrived rather than trusting the declaration.
|
|
159
|
+
const message = isJsonObject(error)
|
|
160
|
+
? readIdentifier(error, "message")
|
|
161
|
+
: undefined;
|
|
162
|
+
return { ok: false, error: message ?? String(error) };
|
|
97
163
|
}
|
|
98
164
|
const user = data?.user;
|
|
99
165
|
if (!user?.id) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"supabase-provider.js","sourceRoot":"","sources":["../../src/providers/supabase-provider.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"supabase-provider.js","sourceRoot":"","sources":["../../src/providers/supabase-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,YAAY,EAAc,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAC1E,OAAO,EACL,YAAY,EACZ,cAAc,EACd,UAAU,EAGX,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