@dokebi/oauth 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/dist/store.js ADDED
@@ -0,0 +1,266 @@
1
+ import { OAuthError, RETRY_AFTER_MS } from './errors.js';
2
+ import { LIMITS_DEFAULT } from './options.js';
3
+ /**
4
+ * How long a registered client is kept after its last use (R5-OAUTH-5, user decision c):
5
+ * `clientUnusedMs`, but never less than `refreshMs` — its last use at the token endpoint may have
6
+ * given it a refresh token that runs that long. Every store and purge use this one value.
7
+ */
8
+ export function clientKeptMs(clientUnusedMs, refreshMs) {
9
+ return Math.max(clientUnusedMs, refreshMs ?? 0);
10
+ }
11
+ // ---- Row checks ---------------------------------------------------------------------------------
12
+ const time = (value, nullable) => (nullable && value === null) || Number.isFinite(value);
13
+ const text = (value, nullable) => (nullable && value === null) || typeof value === 'string';
14
+ const list = (value) => Array.isArray(value) && value.every((item) => typeof item === 'string');
15
+ function invalid(store, what) {
16
+ return new OAuthError('STORE_INVALID', `The ${store} OAuth store returned an invalid ${what}`, {
17
+ fix: `Return rows of the ${what} shape (@dokebi/oauth) from the ${store} store.`,
18
+ data: { store },
19
+ });
20
+ }
21
+ export function checkGrant(value, store) {
22
+ const row = value;
23
+ if (row === null ||
24
+ typeof row !== 'object' ||
25
+ !text(row.id, false) ||
26
+ !text(row.realm, false) ||
27
+ !text(row.userId, false) ||
28
+ !text(row.clientId, false) ||
29
+ !text(row.clientName, false) ||
30
+ !text(row.resource, false) ||
31
+ !list(row.scopes) ||
32
+ !text(row.kind, true) ||
33
+ !text(row.binding, true) ||
34
+ !time(row.createdAt, false) ||
35
+ !time(row.expiresAt, false) ||
36
+ !time(row.lastUsedAt, true) ||
37
+ !time(row.revokedAt, true))
38
+ throw invalid(store, 'GrantRow');
39
+ return row;
40
+ }
41
+ export function checkCode(value, store) {
42
+ const row = value;
43
+ if (row === null ||
44
+ typeof row !== 'object' ||
45
+ !text(row.hash, false) ||
46
+ !text(row.grantId, false) ||
47
+ !text(row.realm, false) ||
48
+ !text(row.userId, false) ||
49
+ !text(row.clientId, false) ||
50
+ !text(row.redirectUri, false) ||
51
+ !text(row.challenge, false) ||
52
+ !text(row.resource, false) ||
53
+ !list(row.scopes) ||
54
+ !time(row.createdAt, false) ||
55
+ !time(row.expiresAt, false) ||
56
+ !time(row.usedAt, true))
57
+ throw invalid(store, 'CodeRow');
58
+ return row;
59
+ }
60
+ export function checkClient(value, store) {
61
+ const row = value;
62
+ if (row === null ||
63
+ typeof row !== 'object' ||
64
+ !text(row.id, false) ||
65
+ !text(row.name, false) ||
66
+ !list(row.redirectUris) ||
67
+ !time(row.createdAt, false) ||
68
+ !time(row.lastUsedAt, false))
69
+ throw invalid(store, 'ClientRow');
70
+ return row;
71
+ }
72
+ // ---- The memory store ---------------------------------------------------------------------------
73
+ const userKey = (realm, userId) => `${realm}\u0000${userId}`;
74
+ /** 503: a bounded store cannot take one more grant or client (`data.limit`). */
75
+ function storeFull(limit, max, retryAfterMs) {
76
+ return new OAuthError('STORE_FULL', 'The OAuth store cannot take more now', {
77
+ status: 503,
78
+ hint: 'Try again later, or remove connections you no longer use.',
79
+ data: { limit, max, retryAfterMs },
80
+ });
81
+ }
82
+ const live = (row, now) => row.revokedAt === null && row.expiresAt > now;
83
+ /** Defaults of the memory store's `maxCodes` and `maxClients` (D-0113 §5). */
84
+ const MAX_CODES = LIMITS_DEFAULT.maxCodes;
85
+ const MAX_CLIENTS = LIMITS_DEFAULT.maxClients;
86
+ function freezeGrant(row) {
87
+ return Object.freeze({ ...row, scopes: Object.freeze([...row.scopes]) });
88
+ }
89
+ /** In process memory: exact and atomic in one process, gone on restart, not shared by workers. */
90
+ export class MemoryOAuthStore {
91
+ name = 'memory';
92
+ #maxGrants;
93
+ #maxPerUser;
94
+ #maxClients;
95
+ #maxCodes;
96
+ #fullRetryAfterMs;
97
+ #grants = new Map();
98
+ #users = new Map();
99
+ #codes = new Map();
100
+ #clients = new Map();
101
+ /**
102
+ * `maxGrants`, `maxGrantsPerUser`, `maxClients`, `maxCodes` and `fullRetryAfterMs`
103
+ * (`storeFullRetryAfterMs`) come from dokebi.yaml (D-0113 §5).
104
+ */
105
+ constructor(maxGrants = 100_000, maxGrantsPerUser = 100, maxClients = MAX_CLIENTS, limits = {}) {
106
+ this.#maxGrants = maxGrants;
107
+ this.#maxPerUser = maxGrantsPerUser;
108
+ this.#maxClients = maxClients;
109
+ this.#maxCodes = limits.maxCodes ?? MAX_CODES;
110
+ this.#fullRetryAfterMs = limits.fullRetryAfterMs ?? RETRY_AFTER_MS.STORE_FULL;
111
+ }
112
+ /**
113
+ * Room for one more grant of this user: the user's own dead grants go, then the user's cap;
114
+ * when the store is full, dead grants of everybody go. A live grant is never dropped: a grant
115
+ * that does not fit is refused (STORE_FULL).
116
+ */
117
+ #makeRoom(row) {
118
+ const now = Date.now();
119
+ let mine = 0;
120
+ for (const id of [...(this.#users.get(userKey(row.realm, row.userId)) ?? [])]) {
121
+ const known = this.#grants.get(id);
122
+ if (!known)
123
+ continue;
124
+ if (live(known, now))
125
+ mine++;
126
+ else
127
+ this.#drop(known);
128
+ }
129
+ if (mine >= this.#maxPerUser)
130
+ throw storeFull('user', this.#maxPerUser, this.#fullRetryAfterMs);
131
+ if (this.#grants.size < this.#maxGrants)
132
+ return;
133
+ for (const known of [...this.#grants.values()])
134
+ if (!live(known, now))
135
+ this.#drop(known);
136
+ if (this.#grants.size >= this.#maxGrants)
137
+ throw storeFull('grants', this.#maxGrants, this.#fullRetryAfterMs);
138
+ }
139
+ #drop(row) {
140
+ this.#grants.delete(row.id);
141
+ const key = userKey(row.realm, row.userId);
142
+ const set = this.#users.get(key);
143
+ set?.delete(row.id);
144
+ if (set?.size === 0)
145
+ this.#users.delete(key);
146
+ }
147
+ insertGrant(row) {
148
+ try {
149
+ this.#makeRoom(row);
150
+ }
151
+ catch (error) {
152
+ return Promise.reject(error);
153
+ }
154
+ this.#grants.set(row.id, freezeGrant(row));
155
+ const key = userKey(row.realm, row.userId);
156
+ let set = this.#users.get(key);
157
+ if (!set) {
158
+ set = new Set();
159
+ this.#users.set(key, set);
160
+ }
161
+ set.add(row.id);
162
+ return Promise.resolve();
163
+ }
164
+ findGrant(id) {
165
+ return Promise.resolve(this.#grants.get(id));
166
+ }
167
+ listGrants(realm, userId) {
168
+ const rows = [];
169
+ for (const id of this.#users.get(userKey(realm, userId)) ?? []) {
170
+ const row = this.#grants.get(id);
171
+ if (row)
172
+ rows.push(row);
173
+ }
174
+ return Promise.resolve(rows);
175
+ }
176
+ revokeGrant(id, at) {
177
+ const row = this.#grants.get(id);
178
+ if (!row || row.revokedAt !== null)
179
+ return Promise.resolve(false);
180
+ this.#grants.set(id, freezeGrant({ ...row, revokedAt: at }));
181
+ return Promise.resolve(true);
182
+ }
183
+ touchGrant(id, at) {
184
+ const row = this.#grants.get(id);
185
+ if (row)
186
+ this.#grants.set(id, freezeGrant({ ...row, lastUsedAt: at }));
187
+ return Promise.resolve();
188
+ }
189
+ insertCode(row) {
190
+ if (this.#codes.size >= this.#maxCodes) {
191
+ const now = Date.now();
192
+ for (const code of [...this.#codes.values()])
193
+ if (code.expiresAt <= now)
194
+ this.#codes.delete(code.hash);
195
+ const oldest = this.#codes.keys().next();
196
+ if (this.#codes.size >= this.#maxCodes && !oldest.done)
197
+ this.#codes.delete(oldest.value);
198
+ }
199
+ this.#codes.set(row.hash, Object.freeze({ ...row, scopes: Object.freeze([...row.scopes]) }));
200
+ return Promise.resolve();
201
+ }
202
+ findCode(hash) {
203
+ return Promise.resolve(this.#codes.get(hash));
204
+ }
205
+ consumeCode(hash, at) {
206
+ // Synchronous between the read and the write: atomic within the process.
207
+ const row = this.#codes.get(hash);
208
+ if (!row)
209
+ return Promise.resolve(undefined);
210
+ if (row.usedAt !== null)
211
+ return Promise.resolve({ row, first: false });
212
+ this.#codes.set(hash, Object.freeze({ ...row, usedAt: at }));
213
+ return Promise.resolve({ row, first: true });
214
+ }
215
+ insertClient(row) {
216
+ if (this.#clients.size >= this.#maxClients) {
217
+ // The oldest client without a live grant makes room; one that holds a grant never goes.
218
+ const now = Date.now();
219
+ const holding = new Set();
220
+ for (const grant of this.#grants.values())
221
+ if (live(grant, now))
222
+ holding.add(grant.clientId);
223
+ let freed = false;
224
+ for (const id of this.#clients.keys())
225
+ if (!holding.has(id)) {
226
+ this.#clients.delete(id);
227
+ freed = true;
228
+ break;
229
+ }
230
+ if (!freed)
231
+ return Promise.reject(storeFull('clients', this.#maxClients, this.#fullRetryAfterMs));
232
+ }
233
+ this.#clients.set(row.id, Object.freeze({ ...row, redirectUris: Object.freeze([...row.redirectUris]) }));
234
+ return Promise.resolve();
235
+ }
236
+ findClient(id) {
237
+ return Promise.resolve(this.#clients.get(id));
238
+ }
239
+ touchClient(id, at) {
240
+ const row = this.#clients.get(id);
241
+ if (row)
242
+ this.#clients.set(id, Object.freeze({ ...row, lastUsedAt: at }));
243
+ return Promise.resolve();
244
+ }
245
+ purge(settings) {
246
+ let grants = 0;
247
+ let codes = 0;
248
+ let clients = 0;
249
+ for (const row of [...this.#grants.values()])
250
+ if (row.revokedAt !== null || row.expiresAt <= settings.now) {
251
+ this.#drop(row);
252
+ grants++;
253
+ }
254
+ for (const row of [...this.#codes.values()])
255
+ if (row.expiresAt + settings.codeGraceMs <= settings.now) {
256
+ this.#codes.delete(row.hash);
257
+ codes++;
258
+ }
259
+ for (const row of [...this.#clients.values()])
260
+ if (row.lastUsedAt + settings.clientUnusedMs <= settings.now) {
261
+ this.#clients.delete(row.id);
262
+ clients++;
263
+ }
264
+ return Promise.resolve({ grants, codes, clients });
265
+ }
266
+ }