ark-oauth-client-node 0.0.0-stage → 2.2.1
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/CHANGELOG.md +84 -0
- package/LICENSE +21 -0
- package/README.md +528 -2
- package/package.json +64 -4
- package/src/access.js +234 -0
- package/src/app-config.js +73 -0
- package/src/client.js +780 -0
- package/src/config.js +164 -0
- package/src/crypto.js +59 -0
- package/src/denied-page.js +83 -0
- package/src/discovery.js +101 -0
- package/src/errors.js +88 -0
- package/src/express.js +820 -0
- package/src/http.js +153 -0
- package/src/index.js +42 -0
- package/src/jwks.js +122 -0
- package/src/jwt.js +294 -0
- package/src/pkce.js +42 -0
- package/src/session.js +135 -0
- package/src/tokens.js +120 -0
- package/src/version.js +10 -0
- package/types/index.d.ts +672 -0
package/src/session.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { createHmac } from 'node:crypto';
|
|
2
|
+
import { base64UrlEncode, fixedTimeEqual, randomToken } from './crypto.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Where a signed-in user's tokens live between requests.
|
|
6
|
+
*
|
|
7
|
+
* The tokens themselves never go to the browser. The cookie carries an opaque session id and a
|
|
8
|
+
* signature over it, and everything else — access token, refresh token, ID token claims — stays in
|
|
9
|
+
* the store on the server. That ordering is the point: a cookie the client can read is a cookie an
|
|
10
|
+
* XSS bug can exfiltrate, and a refresh token in one is a session that outlives the fix.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The default store: a Map with expiry, good for one process.
|
|
15
|
+
*
|
|
16
|
+
* Fine for a single instance and for development. Behind a load balancer, or across a restart,
|
|
17
|
+
* every session lives in one process's heap and disappears with it — supply a shared store (Redis,
|
|
18
|
+
* a database table) with the same four methods for anything that runs more than once.
|
|
19
|
+
*/
|
|
20
|
+
export class MemorySessionStore {
|
|
21
|
+
#entries = new Map();
|
|
22
|
+
#sweepTimer = null;
|
|
23
|
+
|
|
24
|
+
constructor({ sweepIntervalMs = 60_000 } = {}) {
|
|
25
|
+
if (sweepIntervalMs > 0) {
|
|
26
|
+
this.#sweepTimer = setInterval(() => this.sweep(), sweepIntervalMs);
|
|
27
|
+
// Never hold the process open just to expire sessions.
|
|
28
|
+
this.#sweepTimer.unref?.();
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async get(id) {
|
|
33
|
+
const entry = this.#entries.get(id);
|
|
34
|
+
if (!entry) return null;
|
|
35
|
+
if (entry.expiresAt <= Date.now()) {
|
|
36
|
+
this.#entries.delete(id);
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
return entry.data;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async set(id, data, ttlSeconds) {
|
|
43
|
+
this.#entries.set(id, { data, expiresAt: Date.now() + ttlSeconds * 1000 });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async destroy(id) {
|
|
47
|
+
this.#entries.delete(id);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async touch(id, ttlSeconds) {
|
|
51
|
+
const entry = this.#entries.get(id);
|
|
52
|
+
if (entry) entry.expiresAt = Date.now() + ttlSeconds * 1000;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
sweep(now = Date.now()) {
|
|
56
|
+
for (const [id, entry] of this.#entries) {
|
|
57
|
+
if (entry.expiresAt <= now) this.#entries.delete(id);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
get size() {
|
|
62
|
+
return this.#entries.size;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Stops the sweep timer — for tests and for a clean shutdown. */
|
|
66
|
+
close() {
|
|
67
|
+
if (this.#sweepTimer) clearInterval(this.#sweepTimer);
|
|
68
|
+
this.#sweepTimer = null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A fresh session id: 32 random bytes, never derived from anything about the user. */
|
|
73
|
+
export function createSessionId() {
|
|
74
|
+
return randomToken(32);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Signs a session id for the cookie.
|
|
79
|
+
*
|
|
80
|
+
* The signature is not confidentiality — the id is opaque and means nothing on its own. It stops
|
|
81
|
+
* the store being probed with guessed ids, so an attacker cannot mine for a live session by
|
|
82
|
+
* sending a stream of cookies and watching which ones take longer to come back.
|
|
83
|
+
*/
|
|
84
|
+
export function signSessionId(id, secret) {
|
|
85
|
+
const mac = createHmac('sha256', secret).update(id).digest();
|
|
86
|
+
return `${id}.${base64UrlEncode(mac)}`;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Verifies a cookie value and returns the session id, or null when the signature does not hold. */
|
|
90
|
+
export function unsignSessionId(value, secret) {
|
|
91
|
+
if (typeof value !== 'string') return null;
|
|
92
|
+
const dot = value.lastIndexOf('.');
|
|
93
|
+
if (dot <= 0) return null;
|
|
94
|
+
const id = value.slice(0, dot);
|
|
95
|
+
return fixedTimeEqual(value, signSessionId(id, secret)) ? id : null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Parses a Cookie header. */
|
|
99
|
+
export function parseCookies(header) {
|
|
100
|
+
const out = {};
|
|
101
|
+
if (!header) return out;
|
|
102
|
+
for (const part of String(header).split(';')) {
|
|
103
|
+
const eq = part.indexOf('=');
|
|
104
|
+
if (eq < 0) continue;
|
|
105
|
+
const key = part.slice(0, eq).trim();
|
|
106
|
+
if (!key || key in out) continue;
|
|
107
|
+
try {
|
|
108
|
+
out[key] = decodeURIComponent(part.slice(eq + 1).trim());
|
|
109
|
+
} catch {
|
|
110
|
+
out[key] = part.slice(eq + 1).trim();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Builds a Set-Cookie value. */
|
|
117
|
+
export function serializeCookie(name, value, options = {}) {
|
|
118
|
+
const { maxAge, domain, path = '/', expires, httpOnly = true, secure = true, sameSite = 'Lax' } = options;
|
|
119
|
+
const parts = [`${name}=${encodeURIComponent(value)}`];
|
|
120
|
+
if (path) parts.push(`Path=${path}`);
|
|
121
|
+
if (domain) parts.push(`Domain=${domain}`);
|
|
122
|
+
if (maxAge !== undefined) parts.push(`Max-Age=${Math.floor(maxAge)}`);
|
|
123
|
+
if (expires) parts.push(`Expires=${new Date(expires).toUTCString()}`);
|
|
124
|
+
if (httpOnly) parts.push('HttpOnly');
|
|
125
|
+
if (secure) parts.push('Secure');
|
|
126
|
+
if (sameSite) parts.push(`SameSite=${sameSite}`);
|
|
127
|
+
return parts.join('; ');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Appends a Set-Cookie header without dropping any already set on the response. */
|
|
131
|
+
export function appendCookie(res, cookie) {
|
|
132
|
+
const existing = res.getHeader('Set-Cookie');
|
|
133
|
+
if (!existing) res.setHeader('Set-Cookie', [cookie]);
|
|
134
|
+
else res.setHeader('Set-Cookie', Array.isArray(existing) ? [...existing, cookie] : [existing, cookie]);
|
|
135
|
+
}
|
package/src/tokens.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { decodeJwt } from './jwt.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* One token endpoint response, with the parts an application actually asks for.
|
|
5
|
+
*
|
|
6
|
+
* `expires_in` is converted to an absolute `expiresAt` the moment the response arrives. A relative
|
|
7
|
+
* lifetime is only meaningful at the instant it is received, and a token set that has sat in a
|
|
8
|
+
* session store for six minutes cannot answer "are you still valid" from a number that was
|
|
9
|
+
* relative to a moment nobody recorded.
|
|
10
|
+
*/
|
|
11
|
+
export class TokenSet {
|
|
12
|
+
/**
|
|
13
|
+
* @param {object} response the raw JSON from /oauth2/token
|
|
14
|
+
* @param {object} [options]
|
|
15
|
+
* @param {number} [options.issuedAt] epoch seconds; defaults to now
|
|
16
|
+
* @param {object} [options.claims] validated ID token claims, when there was an ID token
|
|
17
|
+
*/
|
|
18
|
+
constructor(response = {}, { issuedAt = Math.floor(Date.now() / 1000), claims = null } = {}) {
|
|
19
|
+
this.accessToken = response.access_token ?? null;
|
|
20
|
+
this.tokenType = response.token_type ?? 'Bearer';
|
|
21
|
+
this.refreshToken = response.refresh_token ?? null;
|
|
22
|
+
this.idToken = response.id_token ?? null;
|
|
23
|
+
this.scope = response.scope ?? null;
|
|
24
|
+
this.issuedAt = issuedAt;
|
|
25
|
+
this.expiresAt =
|
|
26
|
+
typeof response.expires_in === 'number'
|
|
27
|
+
? issuedAt + response.expires_in
|
|
28
|
+
: (response.expires_at ?? null);
|
|
29
|
+
|
|
30
|
+
/** Validated ID token claims — who the user is. Null for a client credentials or API token. */
|
|
31
|
+
this.claims = claims;
|
|
32
|
+
|
|
33
|
+
/** Anything else the server returned, so a provider extension is never silently dropped. */
|
|
34
|
+
this.raw = response;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Seconds until expiry; negative once it has passed. Null when the server gave no lifetime. */
|
|
38
|
+
expiresIn(now = Math.floor(Date.now() / 1000)) {
|
|
39
|
+
return this.expiresAt === null ? null : this.expiresAt - now;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Whether the access token should be treated as spent.
|
|
44
|
+
*
|
|
45
|
+
* `leewaySeconds` exists so a token is renewed *before* it dies rather than after: a token with
|
|
46
|
+
* four seconds left will not survive the downstream call it is about to be attached to.
|
|
47
|
+
*/
|
|
48
|
+
expired(leewaySeconds = 0, now = Math.floor(Date.now() / 1000)) {
|
|
49
|
+
if (this.expiresAt === null) return false;
|
|
50
|
+
return now >= this.expiresAt - leewaySeconds;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The granted scopes, as an array. */
|
|
54
|
+
scopes() {
|
|
55
|
+
return this.scope ? this.scope.split(' ').filter(Boolean) : [];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
hasScope(...wanted) {
|
|
59
|
+
const granted = new Set(this.scopes());
|
|
60
|
+
return wanted.flat().every((s) => granted.has(s));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The tenant's authorization claims from the access token — Ark's `ark_claims`.
|
|
65
|
+
*
|
|
66
|
+
* These, not the scopes, are what an application authorises against: scopes say what the client
|
|
67
|
+
* asked for, `ark_claims` says what this user may do in this client.
|
|
68
|
+
*/
|
|
69
|
+
arkClaims() {
|
|
70
|
+
if (!this.accessToken) return [];
|
|
71
|
+
try {
|
|
72
|
+
const { payload } = decodeJwt(this.accessToken);
|
|
73
|
+
const claims = payload.ark_claims;
|
|
74
|
+
if (Array.isArray(claims)) return claims;
|
|
75
|
+
return typeof claims === 'string' ? [claims] : [];
|
|
76
|
+
} catch {
|
|
77
|
+
// A non-JWT access token (another provider's opaque token) simply carries no ark_claims.
|
|
78
|
+
return [];
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The access token's own claims, unverified — for logging and for reading `sub`, never for authorising. */
|
|
83
|
+
accessTokenClaims() {
|
|
84
|
+
if (!this.accessToken) return null;
|
|
85
|
+
try {
|
|
86
|
+
return decodeJwt(this.accessToken).payload;
|
|
87
|
+
} catch {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
get subject() {
|
|
93
|
+
return this.claims?.sub ?? this.accessTokenClaims()?.sub ?? null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The value for an `Authorization` header. */
|
|
97
|
+
authorizationHeader() {
|
|
98
|
+
return `${this.tokenType} ${this.accessToken}`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** JSON-safe, and round-trips through a session store without losing the absolute expiry. */
|
|
102
|
+
toJSON() {
|
|
103
|
+
return {
|
|
104
|
+
access_token: this.accessToken,
|
|
105
|
+
token_type: this.tokenType,
|
|
106
|
+
refresh_token: this.refreshToken,
|
|
107
|
+
id_token: this.idToken,
|
|
108
|
+
scope: this.scope,
|
|
109
|
+
expires_at: this.expiresAt,
|
|
110
|
+
issued_at: this.issuedAt,
|
|
111
|
+
claims: this.claims
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
static fromJSON(data) {
|
|
116
|
+
if (!data) return null;
|
|
117
|
+
if (data instanceof TokenSet) return data;
|
|
118
|
+
return new TokenSet(data, { issuedAt: data.issued_at ?? Math.floor(Date.now() / 1000), claims: data.claims ?? null });
|
|
119
|
+
}
|
|
120
|
+
}
|
package/src/version.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The version of this package, read from its own package.json.
|
|
5
|
+
*
|
|
6
|
+
* Read rather than written here, so `scripts/version.sh set` has one manifest to stamp and this can
|
|
7
|
+
* never drift from what npm published — the Python client's `__version__` did, more than once, and
|
|
8
|
+
* the access-denied page then named the wrong release.
|
|
9
|
+
*/
|
|
10
|
+
export const VERSION = createRequire(import.meta.url)('../package.json').version;
|