@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/AI.md +469 -0
- package/LICENSE +21 -0
- package/README.md +41 -2
- package/dist/bounded.d.ts +9 -0
- package/dist/bounded.js +36 -0
- package/dist/cimd.d.ts +97 -0
- package/dist/cimd.js +384 -0
- package/dist/clients.d.ts +85 -0
- package/dist/clients.js +303 -0
- package/dist/dependency.d.ts +4 -0
- package/dist/dependency.js +14 -0
- package/dist/errors.d.ts +87 -0
- package/dist/errors.js +34 -0
- package/dist/extension.d.ts +161 -0
- package/dist/extension.js +108 -0
- package/dist/grants.d.ts +126 -0
- package/dist/grants.js +280 -0
- package/dist/index.d.ts +48 -0
- package/dist/index.js +28 -0
- package/dist/install.d.ts +33 -0
- package/dist/install.js +112 -0
- package/dist/live.d.ts +47 -0
- package/dist/live.js +105 -0
- package/dist/options.d.ts +173 -0
- package/dist/options.js +521 -0
- package/dist/plugin.d.ts +113 -0
- package/dist/plugin.js +766 -0
- package/dist/protocol.d.ts +81 -0
- package/dist/protocol.js +249 -0
- package/dist/server.d.ts +148 -0
- package/dist/server.js +1516 -0
- package/dist/signin.d.ts +40 -0
- package/dist/signin.js +86 -0
- package/dist/store-redis.d.ts +38 -0
- package/dist/store-redis.js +173 -0
- package/dist/store-sql.d.ts +46 -0
- package/dist/store-sql.js +363 -0
- package/dist/store.d.ts +126 -0
- package/dist/store.js +266 -0
- package/options.schema.json +633 -0
- package/package.json +143 -4
- package/templates/extension.ts +45 -0
- package/templates/migrations/dokebi_oauth.ts +117 -0
package/dist/clients.js
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { http } from '@dokebi/core/libraries';
|
|
3
|
+
import { LruMap } from './bounded.js';
|
|
4
|
+
import { CimdRefusal, DocumentCache, fetchDocument, looksLikeDocumentUrl, } from './cimd.js';
|
|
5
|
+
import { OAuthProtocolError } from './errors.js';
|
|
6
|
+
import { CIMD_LIMITS_DEFAULT, LIMITS_DEFAULT, } from './options.js';
|
|
7
|
+
import { hostOf, redirectProblem } from './protocol.js';
|
|
8
|
+
/** The dynamic registration ids this server makes: `dcr_` and 22 base64url characters. */
|
|
9
|
+
export const DYNAMIC_ID = /^dcr_[A-Za-z0-9_-]{22}$/;
|
|
10
|
+
export function newDynamicId() {
|
|
11
|
+
return `dcr_${randomBytes(16).toString('base64url')}`;
|
|
12
|
+
}
|
|
13
|
+
/** The host a client is known by: the document URL's, else the first redirect URI's. */
|
|
14
|
+
export function clientHost(client) {
|
|
15
|
+
return client.kind === 'document' ? hostOf(client.id) : hostOf(client.redirectUris[0] ?? '');
|
|
16
|
+
}
|
|
17
|
+
/** The default display name (D-0091 §4): host first, the self-declared name after it. */
|
|
18
|
+
export function displayName(client, hookName) {
|
|
19
|
+
if (hookName)
|
|
20
|
+
return hookName;
|
|
21
|
+
if (client.configuredName)
|
|
22
|
+
return client.configuredName;
|
|
23
|
+
const host = clientHost(client) || client.id;
|
|
24
|
+
return client.declaredName ? `${host} (${client.declaredName})` : host;
|
|
25
|
+
}
|
|
26
|
+
export function clientInfo(client, hookName) {
|
|
27
|
+
return Object.freeze({
|
|
28
|
+
id: client.id,
|
|
29
|
+
name: displayName(client, hookName),
|
|
30
|
+
host: clientHost(client),
|
|
31
|
+
declaredName: client.declaredName,
|
|
32
|
+
kind: client.kind,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
/** Defaults of `cimd.refusalCacheMs`, `cimd.maxFetches` and `cimd.maxFetchesPerAddress`. */
|
|
36
|
+
export const REFUSAL_CACHE_MS = CIMD_LIMITS_DEFAULT.refusalCacheMs;
|
|
37
|
+
export const MAX_FETCHES = CIMD_LIMITS_DEFAULT.maxFetches;
|
|
38
|
+
export const MAX_FETCHES_PER_ADDRESS = CIMD_LIMITS_DEFAULT.maxFetchesPerAddress;
|
|
39
|
+
const DOCUMENT_REFUSED = "The client's metadata document cannot be used";
|
|
40
|
+
const BUSY = 'The server is busy checking client documents; try again in a moment';
|
|
41
|
+
export class ClientDirectory {
|
|
42
|
+
#settings;
|
|
43
|
+
#documents;
|
|
44
|
+
#refused;
|
|
45
|
+
/** One fetch per URL at a time: concurrent requests for the same document share it. */
|
|
46
|
+
#inflight = new Map();
|
|
47
|
+
#perAddress;
|
|
48
|
+
#active = 0;
|
|
49
|
+
constructor(settings) {
|
|
50
|
+
this.#settings = settings;
|
|
51
|
+
// D-0113 §5: every count and time of the document check is a `cimd` option.
|
|
52
|
+
this.#documents = new DocumentCache(settings.cimd.maxCached);
|
|
53
|
+
this.#refused = new LruMap(settings.cimd.maxRefused);
|
|
54
|
+
this.#perAddress = new LruMap(settings.maxTrackedAddresses ?? LIMITS_DEFAULT.maxTrackedAddresses);
|
|
55
|
+
}
|
|
56
|
+
/** Whether a client_id is a document URL this server would accept the shape of. */
|
|
57
|
+
isDocument(clientId) {
|
|
58
|
+
return this.#settings.cimd.enabled && looksLikeDocumentUrl(clientId);
|
|
59
|
+
}
|
|
60
|
+
#registered(clientId) {
|
|
61
|
+
const own = Object.hasOwn(this.#settings.registered, clientId)
|
|
62
|
+
? this.#settings.registered[clientId]
|
|
63
|
+
: undefined;
|
|
64
|
+
if (!own)
|
|
65
|
+
return undefined;
|
|
66
|
+
return Object.freeze({
|
|
67
|
+
id: clientId,
|
|
68
|
+
kind: 'registered',
|
|
69
|
+
redirectUris: own.redirectUris,
|
|
70
|
+
configuredName: own.name,
|
|
71
|
+
declaredName: undefined,
|
|
72
|
+
secretSha256: own.secretSha256,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The client of an authorization request, with its redirect URIs: a document is fetched (or
|
|
77
|
+
* taken from the cache) and checked here. `address` (the requesting client's) bounds the
|
|
78
|
+
* fetches one address may start at once.
|
|
79
|
+
*/
|
|
80
|
+
async resolve(clientId, address = '') {
|
|
81
|
+
if (typeof clientId !== 'string' || clientId === '' || clientId.length > 2048)
|
|
82
|
+
return { ok: false, reason: 'unknown', message: 'The request has no usable client_id' };
|
|
83
|
+
const registered = this.#registered(clientId);
|
|
84
|
+
if (registered)
|
|
85
|
+
return { ok: true, client: registered };
|
|
86
|
+
if (this.isDocument(clientId)) {
|
|
87
|
+
const now = Date.now();
|
|
88
|
+
const cached = this.#documents.get(clientId, now);
|
|
89
|
+
if (cached)
|
|
90
|
+
return {
|
|
91
|
+
ok: true,
|
|
92
|
+
cached: true,
|
|
93
|
+
client: this.#fromDocument(clientId, cached.redirectUris, cached.name),
|
|
94
|
+
};
|
|
95
|
+
const refused = this.#refused.get(clientId);
|
|
96
|
+
if (refused && refused.until > now)
|
|
97
|
+
return {
|
|
98
|
+
ok: false,
|
|
99
|
+
reason: 'document',
|
|
100
|
+
message: DOCUMENT_REFUSED,
|
|
101
|
+
problem: refused.error.problem,
|
|
102
|
+
error: refused.error,
|
|
103
|
+
remembered: true,
|
|
104
|
+
};
|
|
105
|
+
const running = this.#inflight.get(clientId);
|
|
106
|
+
if (running)
|
|
107
|
+
return running;
|
|
108
|
+
const key = http.addressKey(address);
|
|
109
|
+
const mine = this.#perAddress.get(key) ?? 0;
|
|
110
|
+
const cimd = this.#settings.cimd;
|
|
111
|
+
if (this.#active >= cimd.maxFetches || mine >= cimd.maxFetchesPerAddress)
|
|
112
|
+
return { ok: false, reason: 'busy', message: BUSY };
|
|
113
|
+
this.#active++;
|
|
114
|
+
this.#perAddress.set(key, mine + 1);
|
|
115
|
+
const work = this.#fetch(clientId, now).finally(() => {
|
|
116
|
+
this.#active--;
|
|
117
|
+
this.#inflight.delete(clientId);
|
|
118
|
+
const left = (this.#perAddress.get(key) ?? 1) - 1;
|
|
119
|
+
if (left > 0)
|
|
120
|
+
this.#perAddress.set(key, left);
|
|
121
|
+
else
|
|
122
|
+
this.#perAddress.delete(key);
|
|
123
|
+
});
|
|
124
|
+
this.#inflight.set(clientId, work);
|
|
125
|
+
return work;
|
|
126
|
+
}
|
|
127
|
+
if (DYNAMIC_ID.test(clientId)) {
|
|
128
|
+
const row = await this.#settings.findDynamic(clientId);
|
|
129
|
+
if (row)
|
|
130
|
+
return { ok: true, client: this.#fromRow(row) };
|
|
131
|
+
}
|
|
132
|
+
return { ok: false, reason: 'unknown', message: 'This server does not know the client' };
|
|
133
|
+
}
|
|
134
|
+
async #fetch(clientId, now) {
|
|
135
|
+
try {
|
|
136
|
+
const fetched = await fetchDocument(clientId, {
|
|
137
|
+
fetch: this.#settings.fetch,
|
|
138
|
+
timeoutMs: this.#settings.cimd.timeoutMs,
|
|
139
|
+
allowHosts: this.#settings.cimd.allowHosts,
|
|
140
|
+
maxBytes: this.#settings.cimd.maxBytes,
|
|
141
|
+
lifetimes: this.#settings.cimd,
|
|
142
|
+
});
|
|
143
|
+
this.#documents.set(clientId, fetched.document, now + fetched.cacheMs);
|
|
144
|
+
return {
|
|
145
|
+
ok: true,
|
|
146
|
+
cached: false,
|
|
147
|
+
bytes: fetched.bytes,
|
|
148
|
+
client: this.#fromDocument(clientId, fetched.document.redirectUris, fetched.document.name),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
if (!(error instanceof CimdRefusal))
|
|
153
|
+
throw error;
|
|
154
|
+
this.#refused.set(clientId, {
|
|
155
|
+
error,
|
|
156
|
+
until: Date.now() + this.#settings.cimd.refusalCacheMs,
|
|
157
|
+
});
|
|
158
|
+
return {
|
|
159
|
+
ok: false,
|
|
160
|
+
reason: 'document',
|
|
161
|
+
message: DOCUMENT_REFUSED,
|
|
162
|
+
problem: error.problem,
|
|
163
|
+
error,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
#fromDocument(id, redirectUris, name) {
|
|
168
|
+
return Object.freeze({
|
|
169
|
+
id,
|
|
170
|
+
kind: 'document',
|
|
171
|
+
redirectUris,
|
|
172
|
+
configuredName: undefined,
|
|
173
|
+
declaredName: name,
|
|
174
|
+
secretSha256: undefined,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
#fromRow(row) {
|
|
178
|
+
return Object.freeze({
|
|
179
|
+
id: row.id,
|
|
180
|
+
kind: 'dynamic',
|
|
181
|
+
redirectUris: row.redirectUris,
|
|
182
|
+
configuredName: undefined,
|
|
183
|
+
declaredName: row.name === '' ? undefined : row.name,
|
|
184
|
+
secretSha256: undefined,
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* A client known without fetching anything (a document client by its URL shape, a dynamic one
|
|
189
|
+
* from the store), for checks after the consent; undefined when unknown.
|
|
190
|
+
*/
|
|
191
|
+
async known(clientId) {
|
|
192
|
+
const registered = this.#registered(clientId);
|
|
193
|
+
if (registered)
|
|
194
|
+
return registered;
|
|
195
|
+
if (this.isDocument(clientId))
|
|
196
|
+
return this.#fromDocument(clientId, [], undefined);
|
|
197
|
+
if (DYNAMIC_ID.test(clientId)) {
|
|
198
|
+
const row = await this.#settings.findDynamic(clientId);
|
|
199
|
+
if (row)
|
|
200
|
+
return this.#fromRow(row);
|
|
201
|
+
}
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Client authentication at /oauth/token and /oauth/revoke (RFC 6749 §2.3): Basic or the body,
|
|
206
|
+
* never both; a confidential client must prove its secret, a public client must not send one.
|
|
207
|
+
* A document client is public and is not fetched here (the code and the grant bind it).
|
|
208
|
+
*/
|
|
209
|
+
async authenticate(params, authorization) {
|
|
210
|
+
let clientId = params.client_id;
|
|
211
|
+
let secret = params.client_secret;
|
|
212
|
+
let basic = false;
|
|
213
|
+
if (typeof authorization === 'string' && /^basic\s/i.test(authorization)) {
|
|
214
|
+
basic = true;
|
|
215
|
+
const decoded = Buffer.from(authorization.slice(6).trim(), 'base64').toString('utf8');
|
|
216
|
+
const at = decoded.indexOf(':');
|
|
217
|
+
if (at < 0)
|
|
218
|
+
throw new OAuthProtocolError('invalid_client', 'The Basic credentials are malformed', {
|
|
219
|
+
basic,
|
|
220
|
+
});
|
|
221
|
+
let id;
|
|
222
|
+
let password;
|
|
223
|
+
try {
|
|
224
|
+
id = decodeURIComponent(decoded.slice(0, at).replace(/\+/g, ' '));
|
|
225
|
+
password = decodeURIComponent(decoded.slice(at + 1).replace(/\+/g, ' '));
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
if (!(error instanceof URIError))
|
|
229
|
+
throw error;
|
|
230
|
+
throw new OAuthProtocolError('invalid_client', 'The Basic credentials are malformed', {
|
|
231
|
+
basic,
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
if (secret !== undefined)
|
|
235
|
+
throw new OAuthProtocolError('invalid_request', 'The client authenticated twice (Basic and client_secret); use one method');
|
|
236
|
+
if (clientId !== undefined && clientId !== id)
|
|
237
|
+
throw new OAuthProtocolError('invalid_client', 'client_id differs from the Basic credentials', {
|
|
238
|
+
basic,
|
|
239
|
+
});
|
|
240
|
+
clientId = id;
|
|
241
|
+
secret = password;
|
|
242
|
+
}
|
|
243
|
+
if (clientId === undefined || clientId === '')
|
|
244
|
+
throw new OAuthProtocolError('invalid_client', 'The request has no client_id', { basic });
|
|
245
|
+
const client = await this.known(clientId);
|
|
246
|
+
if (!client)
|
|
247
|
+
throw new OAuthProtocolError('invalid_client', 'This server does not know the client', {
|
|
248
|
+
basic,
|
|
249
|
+
});
|
|
250
|
+
if (client.secretSha256 !== undefined) {
|
|
251
|
+
if (secret === undefined)
|
|
252
|
+
throw new OAuthProtocolError('invalid_client', 'This client must authenticate with its secret', {
|
|
253
|
+
basic,
|
|
254
|
+
});
|
|
255
|
+
const presented = Buffer.from(createHash('sha256').update(secret, 'utf8').digest('hex'), 'ascii');
|
|
256
|
+
const expected = Buffer.from(client.secretSha256, 'ascii');
|
|
257
|
+
if (presented.length !== expected.length || !timingSafeEqual(presented, expected))
|
|
258
|
+
throw new OAuthProtocolError('invalid_client', 'The client secret is wrong', { basic });
|
|
259
|
+
}
|
|
260
|
+
else if (secret !== undefined)
|
|
261
|
+
throw new OAuthProtocolError('invalid_client', 'A public client sends no secret (token_endpoint_auth_method none)', { basic });
|
|
262
|
+
return client;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
/** Checks a registration body; an RFC 7591 error otherwise. */
|
|
266
|
+
export function checkRegistration(body) {
|
|
267
|
+
if (body === null || typeof body !== 'object' || Array.isArray(body))
|
|
268
|
+
throw new OAuthProtocolError('invalid_client_metadata', 'The registration is not a JSON object');
|
|
269
|
+
const value = body;
|
|
270
|
+
const redirects = value.redirect_uris;
|
|
271
|
+
if (!Array.isArray(redirects) ||
|
|
272
|
+
redirects.length === 0 ||
|
|
273
|
+
redirects.length > 16 ||
|
|
274
|
+
redirects.some((item) => typeof item !== 'string'))
|
|
275
|
+
throw new OAuthProtocolError('invalid_redirect_uri', 'redirect_uris must be 1 to 16 strings');
|
|
276
|
+
for (const uri of redirects) {
|
|
277
|
+
const problem = redirectProblem(uri);
|
|
278
|
+
if (problem)
|
|
279
|
+
throw new OAuthProtocolError('invalid_redirect_uri', problem);
|
|
280
|
+
}
|
|
281
|
+
const method = value.token_endpoint_auth_method;
|
|
282
|
+
if (method !== undefined && method !== 'none')
|
|
283
|
+
throw new OAuthProtocolError('invalid_client_metadata', 'Only public clients register here (token_endpoint_auth_method none)');
|
|
284
|
+
const grants = value.grant_types;
|
|
285
|
+
if (grants !== undefined &&
|
|
286
|
+
(!Array.isArray(grants) ||
|
|
287
|
+
grants.some((item) => typeof item !== 'string') ||
|
|
288
|
+
!grants.includes('authorization_code')))
|
|
289
|
+
throw new OAuthProtocolError('invalid_client_metadata', 'grant_types must contain authorization_code');
|
|
290
|
+
const responses = value.response_types;
|
|
291
|
+
if (responses !== undefined &&
|
|
292
|
+
(!Array.isArray(responses) ||
|
|
293
|
+
responses.some((item) => typeof item !== 'string') ||
|
|
294
|
+
!responses.includes('code')))
|
|
295
|
+
throw new OAuthProtocolError('invalid_client_metadata', 'response_types must contain code');
|
|
296
|
+
const name = value.client_name;
|
|
297
|
+
if (name !== undefined && (typeof name !== 'string' || name.trim() === '' || name.length > 255))
|
|
298
|
+
throw new OAuthProtocolError('invalid_client_metadata', 'client_name must be 1 to 255 characters');
|
|
299
|
+
return Object.freeze({
|
|
300
|
+
name: typeof name === 'string' ? name.trim() : '',
|
|
301
|
+
redirectUris: Object.freeze([...redirects]),
|
|
302
|
+
});
|
|
303
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { OAuthApi } from './plugin.js';
|
|
2
|
+
export declare const provider: import("@dokebi/core").ProviderDescriptor<OAuthApi>;
|
|
3
|
+
/** Required: created from @dokebi/oauth when no `dokebi-oauth` plugin is registered. */
|
|
4
|
+
export declare const dependency: import("@dokebi/core").PluginDependency<OAuthApi>;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { defineProvider } from '@dokebi/core';
|
|
2
|
+
/*
|
|
3
|
+
* The one place dokebi-oauth states its name, package and range (D-0063 §6). Plugins that always
|
|
4
|
+
* install @dokebi/oauth (the future @dokebi/mcp) import `dependency` from
|
|
5
|
+
* '@dokebi/oauth/dependency' (a small module: it loads nothing else).
|
|
6
|
+
*/
|
|
7
|
+
export const provider = defineProvider({
|
|
8
|
+
name: 'dokebi-oauth',
|
|
9
|
+
version: '^0.1.0',
|
|
10
|
+
packageName: '@dokebi/oauth',
|
|
11
|
+
load: () => import('./index.js'),
|
|
12
|
+
});
|
|
13
|
+
/** Required: created from @dokebi/oauth when no `dokebi-oauth` plugin is registered. */
|
|
14
|
+
export const dependency = provider.dependency;
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { DokebiError, type DokebiErrorOptions } from '@dokebi/core';
|
|
2
|
+
export type OAuthErrorCode =
|
|
3
|
+
/** Start: options that the schema cannot judge (issuer scheme, resource URIs, scopes, clients). */
|
|
4
|
+
'INVALID_OPTIONS'
|
|
5
|
+
/** The entry module (src/infra/oauth/extension.ts) has the wrong shape. */
|
|
6
|
+
| 'INVALID_ENTRY'
|
|
7
|
+
/** The extension class does not implement `renderConsent`. */
|
|
8
|
+
| 'EXTENSION_REQUIRED'
|
|
9
|
+
/** A hook returned something the plugin cannot use (`data.hook` names it). */
|
|
10
|
+
| 'INVALID_HOOK_RESULT'
|
|
11
|
+
/** A hook threw; the cause is attached and logged in full. */
|
|
12
|
+
| 'HOOK_FAILED'
|
|
13
|
+
/** Start: `store.driver: sql` and a table does not exist (run the migration). */
|
|
14
|
+
| 'TABLE_MISSING'
|
|
15
|
+
/** Start: the sql store's connection is not a pg, mysql2 or mariadb pool (MongoDB included). */
|
|
16
|
+
| 'UNSUPPORTED_RESOURCE'
|
|
17
|
+
/** A sql store call in a describing app (`dokebi describe`, D-0133): no query runs there. */
|
|
18
|
+
| 'DESCRIBING'
|
|
19
|
+
/** The grant store did not answer (503); the cause is attached. */
|
|
20
|
+
| 'STORE_FAILED'
|
|
21
|
+
/** The store returned a row of the wrong shape. */
|
|
22
|
+
| 'STORE_INVALID'
|
|
23
|
+
/**
|
|
24
|
+
* 503: the memory store cannot take one more grant (the user's `maxGrantsPerUser` or
|
|
25
|
+
* `maxGrants` of live grants) or registered client (all of them hold grants); `data.limit`.
|
|
26
|
+
*/
|
|
27
|
+
| 'STORE_FULL'
|
|
28
|
+
/** Start: a route's `config.oauth` is wrong (unknown resource, undeclared scope). */
|
|
29
|
+
| 'INVALID_ROUTE_CONFIG'
|
|
30
|
+
/** Start: `rateLimit` is set and @dokebi/rate-limit is not registered (or has no such policy). */
|
|
31
|
+
| 'RATE_LIMIT_REQUIRED'
|
|
32
|
+
/**
|
|
33
|
+
* 400: GET /oauth/authorize refused before the client and its redirect URI were verified (an
|
|
34
|
+
* unknown client, a refused metadata document, a redirect URI that is not registered, a
|
|
35
|
+
* repeated parameter). Shown as a page: never redirected (that would be an open redirect).
|
|
36
|
+
*/
|
|
37
|
+
| 'AUTHORIZE_REFUSED'
|
|
38
|
+
/** 400: the consent request is unknown or older than 10 minutes, or was decided already. */
|
|
39
|
+
| 'CONSENT_EXPIRED'
|
|
40
|
+
/** 400: the consent decision asks for scopes that were not requested, or for none, or a bad kind or binding. */
|
|
41
|
+
| 'INVALID_CONSENT'
|
|
42
|
+
/** 403: the consent is decided by another user than the one who opened it. */
|
|
43
|
+
| 'FORBIDDEN'
|
|
44
|
+
/**
|
|
45
|
+
* 401 on a protected route: no token, or a token that is not valid for this resource (any
|
|
46
|
+
* reason; the reason is only in the debug log). `WWW-Authenticate: Bearer resource_metadata=…`.
|
|
47
|
+
*/
|
|
48
|
+
| 'UNAUTHENTICATED'
|
|
49
|
+
/** 403 on a protected route: the grant does not hold the route's scopes (`error="insufficient_scope"`). */
|
|
50
|
+
| 'INSUFFICIENT_SCOPE'
|
|
51
|
+
/**
|
|
52
|
+
* 401 on a route with `maxAge` (RFC 9470): the token's sign-in is unknown or older than it
|
|
53
|
+
* (`error="insufficient_user_authentication"`, `max_age`); authorize again with max_age or
|
|
54
|
+
* prompt=login (D-0122).
|
|
55
|
+
*/
|
|
56
|
+
| 'INSUFFICIENT_USER_AUTHENTICATION'
|
|
57
|
+
/** A call of the API with a wrong argument (a user that is not an object, an unknown resource). */
|
|
58
|
+
| 'INVALID_ARGUMENT';
|
|
59
|
+
/**
|
|
60
|
+
* Default of when to try a 503 again (`data.retryAfterMs`; dokebi-web answers it as Retry-After,
|
|
61
|
+
* the D-0102 pattern, D-0109 §7): a store that did not answer, a bounded store that is full for
|
|
62
|
+
* now. dokebi-oauth `storeRetryAfterMs` and `storeFullRetryAfterMs` set them (D-0113 §5).
|
|
63
|
+
*/
|
|
64
|
+
export declare const RETRY_AFTER_MS: Readonly<{
|
|
65
|
+
STORE_FAILED: 1000;
|
|
66
|
+
STORE_FULL: 5000;
|
|
67
|
+
}>;
|
|
68
|
+
export declare class OAuthError extends DokebiError<OAuthErrorCode> {
|
|
69
|
+
constructor(code: OAuthErrorCode, message: string, options?: DokebiErrorOptions);
|
|
70
|
+
}
|
|
71
|
+
/** The RFC error codes this server writes (token, revocation, registration, authorization). */
|
|
72
|
+
export type OAuthProtocolErrorCode = 'invalid_request' | 'invalid_client' | 'invalid_grant' | 'unauthorized_client' | 'unsupported_grant_type' | 'invalid_scope' | 'invalid_target' | 'access_denied' | 'unsupported_response_type' | 'server_error' | 'temporarily_unavailable' | 'invalid_redirect_uri' | 'invalid_client_metadata';
|
|
73
|
+
/** An RFC error answer: written as `{ error, error_description }` with `status`. */
|
|
74
|
+
export declare class OAuthProtocolError extends Error {
|
|
75
|
+
readonly error: OAuthProtocolErrorCode;
|
|
76
|
+
readonly status: number;
|
|
77
|
+
/** Written as `WWW-Authenticate: Basic` for a failed client_secret_basic (RFC 6749 §5.2). */
|
|
78
|
+
readonly basic: boolean;
|
|
79
|
+
/** Written as `Retry-After` (seconds, rounded up) with a 503 `temporarily_unavailable`. */
|
|
80
|
+
readonly retryAfterMs: number | undefined;
|
|
81
|
+
constructor(error: OAuthProtocolErrorCode, description: string, settings?: {
|
|
82
|
+
status?: number;
|
|
83
|
+
basic?: boolean;
|
|
84
|
+
retryAfterMs?: number;
|
|
85
|
+
cause?: unknown;
|
|
86
|
+
});
|
|
87
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { DokebiError } from '@dokebi/core';
|
|
2
|
+
import { LIMITS_DEFAULT } from './options.js';
|
|
3
|
+
/**
|
|
4
|
+
* Default of when to try a 503 again (`data.retryAfterMs`; dokebi-web answers it as Retry-After,
|
|
5
|
+
* the D-0102 pattern, D-0109 §7): a store that did not answer, a bounded store that is full for
|
|
6
|
+
* now. dokebi-oauth `storeRetryAfterMs` and `storeFullRetryAfterMs` set them (D-0113 §5).
|
|
7
|
+
*/
|
|
8
|
+
export const RETRY_AFTER_MS = Object.freeze({
|
|
9
|
+
STORE_FAILED: LIMITS_DEFAULT.storeRetryAfterMs,
|
|
10
|
+
STORE_FULL: LIMITS_DEFAULT.storeFullRetryAfterMs,
|
|
11
|
+
});
|
|
12
|
+
export class OAuthError extends DokebiError {
|
|
13
|
+
constructor(code, message, options = {}) {
|
|
14
|
+
super(code, message, { ...options, plugin: options.plugin ?? 'dokebi-oauth' });
|
|
15
|
+
this.name = 'OAuthError';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/** An RFC error answer: written as `{ error, error_description }` with `status`. */
|
|
19
|
+
export class OAuthProtocolError extends Error {
|
|
20
|
+
error;
|
|
21
|
+
status;
|
|
22
|
+
/** Written as `WWW-Authenticate: Basic` for a failed client_secret_basic (RFC 6749 §5.2). */
|
|
23
|
+
basic;
|
|
24
|
+
/** Written as `Retry-After` (seconds, rounded up) with a 503 `temporarily_unavailable`. */
|
|
25
|
+
retryAfterMs;
|
|
26
|
+
constructor(error, description, settings = {}) {
|
|
27
|
+
super(description, settings.cause === undefined ? undefined : { cause: settings.cause });
|
|
28
|
+
this.name = 'OAuthProtocolError';
|
|
29
|
+
this.error = error;
|
|
30
|
+
this.status = settings.status ?? (error === 'invalid_client' ? 401 : 400);
|
|
31
|
+
this.basic = settings.basic ?? false;
|
|
32
|
+
this.retryAfterMs = settings.retryAfterMs;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import type { ApplicationView, Awaitable, Logger, PluginDependency } from '@dokebi/core';
|
|
2
|
+
import type { FastifyReply, FastifyRequest } from 'fastify';
|
|
3
|
+
/** How the plugin knows a client. */
|
|
4
|
+
export type OAuthClientKind = 'document' | 'registered' | 'dynamic';
|
|
5
|
+
/** A client as hooks and the consent data see it (no secret). */
|
|
6
|
+
export interface OAuthClientInfo {
|
|
7
|
+
/** The client_id (a document URL for `document` clients). */
|
|
8
|
+
readonly id: string;
|
|
9
|
+
/**
|
|
10
|
+
* The name to show: `clientName()` if it gave one, the configured name of a pre-registered
|
|
11
|
+
* client, else the host first with the self-declared name after it (`claude.ai (Claude)`).
|
|
12
|
+
*/
|
|
13
|
+
readonly name: string;
|
|
14
|
+
/** The host the client is known by: the document URL's host, else its first redirect host. */
|
|
15
|
+
readonly host: string;
|
|
16
|
+
/** The name the client gave itself (a document's `client_name`, a registration's), unverified. */
|
|
17
|
+
readonly declaredName: string | undefined;
|
|
18
|
+
readonly kind: OAuthClientKind;
|
|
19
|
+
}
|
|
20
|
+
/** What `renderConsent` gets: everything the page must show, checked by the plugin. */
|
|
21
|
+
export interface OAuthConsent {
|
|
22
|
+
/** The id of this consent request: post it back as the field `request`. */
|
|
23
|
+
readonly id: string;
|
|
24
|
+
/** Where the decision is posted (`POST`): the authorize path. */
|
|
25
|
+
readonly action: string;
|
|
26
|
+
readonly client: OAuthClientInfo;
|
|
27
|
+
/** Where the code goes when the user allows (exactly as registered). */
|
|
28
|
+
readonly redirectUri: string;
|
|
29
|
+
/** **Show it**: the host the code goes to (MCP requires it on the consent screen). */
|
|
30
|
+
readonly redirectHost: string;
|
|
31
|
+
/**
|
|
32
|
+
* True when the redirect URI of this request is a loopback address (the answer goes to this
|
|
33
|
+
* computer); another registered URI of the client may be remote.
|
|
34
|
+
*/
|
|
35
|
+
readonly loopback: boolean;
|
|
36
|
+
/** **Show it** when set: an English sentence warning that the answer goes to this computer. */
|
|
37
|
+
readonly warning: string | undefined;
|
|
38
|
+
readonly resource: {
|
|
39
|
+
readonly id: string;
|
|
40
|
+
readonly uri: string;
|
|
41
|
+
readonly name: string;
|
|
42
|
+
};
|
|
43
|
+
/** The requested scopes with their labels; allow a subset of these names only. */
|
|
44
|
+
readonly scopes: readonly {
|
|
45
|
+
readonly name: string;
|
|
46
|
+
readonly label: string;
|
|
47
|
+
}[];
|
|
48
|
+
/** The signed-in user's id (the realm's `credentials(user).id`). */
|
|
49
|
+
readonly userId: string;
|
|
50
|
+
/**
|
|
51
|
+
* What this user allowed this client for this resource before: the newest live grant of them,
|
|
52
|
+
* when there is one (prefill the page). Allowing makes a new grant (D-0124: one per
|
|
53
|
+
* authorization, so another device keeps its own); this one stays.
|
|
54
|
+
*/
|
|
55
|
+
readonly grant: {
|
|
56
|
+
readonly id: string;
|
|
57
|
+
readonly scopes: readonly string[];
|
|
58
|
+
readonly kind: string | null;
|
|
59
|
+
readonly binding: unknown;
|
|
60
|
+
readonly expiresAt: Date;
|
|
61
|
+
} | undefined;
|
|
62
|
+
/** The request is gone after this (10 minutes). */
|
|
63
|
+
readonly expiresAt: Date;
|
|
64
|
+
/**
|
|
65
|
+
* The form fields the decision posts: `request` (this id), `decision` (`allow` or `deny`),
|
|
66
|
+
* `scope` (allowed scope names, repeated or space-separated; default all requested), `kind`
|
|
67
|
+
* (optional, 1-64 characters) and `binding` (optional JSON text, at most 4 KB). JSON bodies
|
|
68
|
+
* (Inertia) use the same names, `scope` as a list and `binding` as a value.
|
|
69
|
+
*/
|
|
70
|
+
readonly fields: {
|
|
71
|
+
readonly request: 'request';
|
|
72
|
+
readonly decision: 'decision';
|
|
73
|
+
readonly scope: 'scope';
|
|
74
|
+
readonly kind: 'kind';
|
|
75
|
+
readonly binding: 'binding';
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** What `checkDecision` judges: the allowed scopes and what the browser posted. */
|
|
79
|
+
export interface OAuthDecision {
|
|
80
|
+
readonly scopes: readonly string[];
|
|
81
|
+
/** The posted `kind`, or null. User-submitted: never trust it unchecked. */
|
|
82
|
+
readonly kind: string | null;
|
|
83
|
+
/** The posted `binding` (parsed JSON), or null. User-submitted: never trust it unchecked. */
|
|
84
|
+
readonly binding: unknown;
|
|
85
|
+
}
|
|
86
|
+
/** What `checkDecision` accepts: stored on the grant (null or absent: none). */
|
|
87
|
+
export interface OAuthAcceptedDecision {
|
|
88
|
+
readonly kind?: string | null;
|
|
89
|
+
readonly binding?: unknown;
|
|
90
|
+
}
|
|
91
|
+
/** What hooks receive besides their input. Never the request (except the render hooks). */
|
|
92
|
+
export interface OAuthHookContext {
|
|
93
|
+
/** The dokebi-auth realm of the grants. */
|
|
94
|
+
readonly realm: string;
|
|
95
|
+
readonly app: ApplicationView;
|
|
96
|
+
/** Providers declared by `dependencies()` (for example @dokebi/template-ejs). */
|
|
97
|
+
getDependency<TApi>(dependency: PluginDependency<TApi>): TApi;
|
|
98
|
+
/** The plugin's logger. */
|
|
99
|
+
readonly logger: Logger;
|
|
100
|
+
/** Aborted when the app stops. */
|
|
101
|
+
readonly signal: AbortSignal;
|
|
102
|
+
}
|
|
103
|
+
/** The hooks the plugin calls, as plain methods (internal: the runtime's view of a subclass). */
|
|
104
|
+
export interface OAuthHooks {
|
|
105
|
+
dependencies(): readonly PluginDependency[];
|
|
106
|
+
renderConsent(request: FastifyRequest, reply: FastifyReply, consent: OAuthConsent, context: OAuthHookContext): Awaitable<unknown>;
|
|
107
|
+
canDelegate(user: unknown, client: OAuthClientInfo, context: OAuthHookContext): Awaitable<unknown>;
|
|
108
|
+
clientName(clientId: string, context: OAuthHookContext): Awaitable<unknown>;
|
|
109
|
+
checkDecision(user: unknown, client: OAuthClientInfo, decision: OAuthDecision, context: OAuthHookContext): Awaitable<unknown>;
|
|
110
|
+
scopeLabel(scope: string, request: FastifyRequest, context: OAuthHookContext): unknown;
|
|
111
|
+
}
|
|
112
|
+
export declare const EXTENSION_FILE = "src/infra/oauth/extension.ts";
|
|
113
|
+
export declare const REQUIRED_HOOKS: readonly ['renderConsent'];
|
|
114
|
+
declare const OAuthExtension_base: import("@dokebi/core").ExtensionRoot;
|
|
115
|
+
/**
|
|
116
|
+
* Subclass this in `src/infra/oauth/extension.ts` (`export default class AppOAuth extends
|
|
117
|
+
* OAuthExtension<UserRow> { … }`) and implement `renderConsent` with `protected override`. The
|
|
118
|
+
* other hooks have defaults. Hooks run with their inputs only: no constructor parameters, and
|
|
119
|
+
* hooks never call each other.
|
|
120
|
+
*/
|
|
121
|
+
export declare class OAuthExtension<User = Record<string, unknown>> extends OAuthExtension_base {
|
|
122
|
+
/**
|
|
123
|
+
* Providers the other hooks use through `context.getDependency` (the template engine of the
|
|
124
|
+
* consent page). Called once when the plugin is created. Default: none.
|
|
125
|
+
*/
|
|
126
|
+
protected dependencies(): readonly PluginDependency[];
|
|
127
|
+
/**
|
|
128
|
+
* **Required.** Renders the consent page for `consent` and sends it (or returns what the route
|
|
129
|
+
* should answer). It must show the client (`consent.client.name`, `client.host`), the redirect
|
|
130
|
+
* host (`consent.redirectHost`), `consent.warning` when set, the resource and the scopes, and
|
|
131
|
+
* post `request` and `decision` (plus the CSRF field of @dokebi/csrf) to `consent.action`.
|
|
132
|
+
*/
|
|
133
|
+
protected renderConsent(request: FastifyRequest, reply: FastifyReply, consent: OAuthConsent, context: OAuthHookContext): Awaitable<unknown>;
|
|
134
|
+
/**
|
|
135
|
+
* May this user hand access to `client`? Called before the consent page and again at the
|
|
136
|
+
* decision and the code exchange (an account suspended meanwhile gets no token). Default:
|
|
137
|
+
* true. False answers `access_denied` to the client.
|
|
138
|
+
*/
|
|
139
|
+
protected canDelegate(user: User, client: OAuthClientInfo, context: OAuthHookContext): Awaitable<boolean>;
|
|
140
|
+
/**
|
|
141
|
+
* Judges the `kind` and `binding` a consent decision posted (both user-submitted). Return the
|
|
142
|
+
* accepted `{ kind, binding }` — validated against what this user may reach — or `false` to
|
|
143
|
+
* refuse the decision (400 INVALID_CONSENT). Without this hook a decision that carries a kind
|
|
144
|
+
* or a binding is refused. The binding is a hint of what the connection reaches: authorize it
|
|
145
|
+
* again on every use, never treat it as a permission.
|
|
146
|
+
*/
|
|
147
|
+
protected checkDecision(user: User, client: OAuthClientInfo, decision: OAuthDecision, context: OAuthHookContext): Awaitable<OAuthAcceptedDecision | false>;
|
|
148
|
+
/**
|
|
149
|
+
* A name for a client_id you know (`'Claude'` for claude.ai's document URL); undefined: the
|
|
150
|
+
* default (host first). Default: undefined.
|
|
151
|
+
*/
|
|
152
|
+
protected clientName(clientId: string, context: OAuthHookContext): Awaitable<string | undefined>;
|
|
153
|
+
/**
|
|
154
|
+
* The label of a scope on this request's consent page (a translation); undefined: the label of
|
|
155
|
+
* `resources.<id>.scopes`. Default: undefined.
|
|
156
|
+
*/
|
|
157
|
+
protected scopeLabel(scope: string, request: FastifyRequest, context: OAuthHookContext): string | undefined;
|
|
158
|
+
}
|
|
159
|
+
/** The plugin's handle on a subclass instance (not exported from the package). */
|
|
160
|
+
export declare function oauthHooks(extension: OAuthExtension<unknown>): OAuthHooks;
|
|
161
|
+
export {};
|