@dokebi/oauth 0.0.0-stage → 0.1.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/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
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { defineExtension } from '@dokebi/core';
|
|
2
|
+
import { OAuthError } from './errors.js';
|
|
3
|
+
export const EXTENSION_FILE = 'src/infra/oauth/extension.ts';
|
|
4
|
+
export const REQUIRED_HOOKS = ['renderConsent'];
|
|
5
|
+
let bridge;
|
|
6
|
+
function required(hook) {
|
|
7
|
+
throw new OAuthError('EXTENSION_REQUIRED', `${hook}() is not implemented`, {
|
|
8
|
+
fix: `Implement protected override ${hook}(…) in ${EXTENSION_FILE}.`,
|
|
9
|
+
data: { hooks: [hook] },
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Subclass this in `src/infra/oauth/extension.ts` (`export default class AppOAuth extends
|
|
14
|
+
* OAuthExtension<UserRow> { … }`) and implement `renderConsent` with `protected override`. The
|
|
15
|
+
* other hooks have defaults. Hooks run with their inputs only: no constructor parameters, and
|
|
16
|
+
* hooks never call each other.
|
|
17
|
+
*/
|
|
18
|
+
export class OAuthExtension extends defineExtension({
|
|
19
|
+
plugin: 'dokebi-oauth',
|
|
20
|
+
api: 1,
|
|
21
|
+
hooks: [
|
|
22
|
+
'dependencies',
|
|
23
|
+
'renderConsent',
|
|
24
|
+
'canDelegate',
|
|
25
|
+
'checkDecision',
|
|
26
|
+
'clientName',
|
|
27
|
+
'scopeLabel',
|
|
28
|
+
],
|
|
29
|
+
file: EXTENSION_FILE,
|
|
30
|
+
}) {
|
|
31
|
+
static {
|
|
32
|
+
bridge = (extension) => Object.freeze({
|
|
33
|
+
dependencies: () => extension.dependencies(),
|
|
34
|
+
renderConsent: (request, reply, consent, context) => extension.renderConsent(request, reply, consent, context),
|
|
35
|
+
canDelegate: (user, client, context) => extension.canDelegate(user, client, context),
|
|
36
|
+
clientName: (clientId, context) => extension.clientName(clientId, context),
|
|
37
|
+
checkDecision: (user, client, decision, context) => extension.checkDecision(user, client, decision, context),
|
|
38
|
+
scopeLabel: (scope, request, context) => extension.scopeLabel(scope, request, context),
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Providers the other hooks use through `context.getDependency` (the template engine of the
|
|
43
|
+
* consent page). Called once when the plugin is created. Default: none.
|
|
44
|
+
*/
|
|
45
|
+
dependencies() {
|
|
46
|
+
return [];
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* **Required.** Renders the consent page for `consent` and sends it (or returns what the route
|
|
50
|
+
* should answer). It must show the client (`consent.client.name`, `client.host`), the redirect
|
|
51
|
+
* host (`consent.redirectHost`), `consent.warning` when set, the resource and the scopes, and
|
|
52
|
+
* post `request` and `decision` (plus the CSRF field of @dokebi/csrf) to `consent.action`.
|
|
53
|
+
*/
|
|
54
|
+
renderConsent(request, reply, consent, context) {
|
|
55
|
+
void request;
|
|
56
|
+
void reply;
|
|
57
|
+
void consent;
|
|
58
|
+
void context;
|
|
59
|
+
return required('renderConsent');
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* May this user hand access to `client`? Called before the consent page and again at the
|
|
63
|
+
* decision and the code exchange (an account suspended meanwhile gets no token). Default:
|
|
64
|
+
* true. False answers `access_denied` to the client.
|
|
65
|
+
*/
|
|
66
|
+
canDelegate(user, client, context) {
|
|
67
|
+
void user;
|
|
68
|
+
void client;
|
|
69
|
+
void context;
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Judges the `kind` and `binding` a consent decision posted (both user-submitted). Return the
|
|
74
|
+
* accepted `{ kind, binding }` — validated against what this user may reach — or `false` to
|
|
75
|
+
* refuse the decision (400 INVALID_CONSENT). Without this hook a decision that carries a kind
|
|
76
|
+
* or a binding is refused. The binding is a hint of what the connection reaches: authorize it
|
|
77
|
+
* again on every use, never treat it as a permission.
|
|
78
|
+
*/
|
|
79
|
+
checkDecision(user, client, decision, context) {
|
|
80
|
+
void user;
|
|
81
|
+
void client;
|
|
82
|
+
void context;
|
|
83
|
+
return decision.kind === null && decision.binding === null ? {} : false;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* A name for a client_id you know (`'Claude'` for claude.ai's document URL); undefined: the
|
|
87
|
+
* default (host first). Default: undefined.
|
|
88
|
+
*/
|
|
89
|
+
clientName(clientId, context) {
|
|
90
|
+
void clientId;
|
|
91
|
+
void context;
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The label of a scope on this request's consent page (a translation); undefined: the label of
|
|
96
|
+
* `resources.<id>.scopes`. Default: undefined.
|
|
97
|
+
*/
|
|
98
|
+
scopeLabel(scope, request, context) {
|
|
99
|
+
void scope;
|
|
100
|
+
void request;
|
|
101
|
+
void context;
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/** The plugin's handle on a subclass instance (not exported from the package). */
|
|
106
|
+
export function oauthHooks(extension) {
|
|
107
|
+
return bridge(extension);
|
|
108
|
+
}
|
package/dist/grants.d.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import type { AuthRealmApi } from '@dokebi/auth';
|
|
2
|
+
import type { Logger } from '@dokebi/core';
|
|
3
|
+
import { diagnostics } from '@dokebi/core/libraries';
|
|
4
|
+
import { LiveGrants } from './live.js';
|
|
5
|
+
import { type GrantRow, type OAuthStore } from './store.js';
|
|
6
|
+
/** A grant as the API and `request.oauth.grant` show it (no secret). */
|
|
7
|
+
export interface OAuthGrant {
|
|
8
|
+
/** Also the token family of its tokens. */
|
|
9
|
+
readonly id: string;
|
|
10
|
+
readonly realm: string;
|
|
11
|
+
readonly userId: string;
|
|
12
|
+
readonly clientId: string;
|
|
13
|
+
readonly clientName: string;
|
|
14
|
+
/** The resource id (`resources.<id>`). */
|
|
15
|
+
readonly resource: string;
|
|
16
|
+
readonly scopes: readonly string[];
|
|
17
|
+
/** The kind the application chose at the consent, or null. */
|
|
18
|
+
readonly kind: string | null;
|
|
19
|
+
/** The application's binding (parsed JSON), or null. */
|
|
20
|
+
readonly binding: unknown;
|
|
21
|
+
readonly createdAt: Date;
|
|
22
|
+
/** The absolute end; refreshes never move it. */
|
|
23
|
+
readonly expiresAt: Date;
|
|
24
|
+
readonly lastUsedAt: Date | null;
|
|
25
|
+
readonly revokedAt: Date | null;
|
|
26
|
+
}
|
|
27
|
+
/** `api.grants`: the grants of the realm's users. */
|
|
28
|
+
export interface OAuthGrants {
|
|
29
|
+
/**
|
|
30
|
+
* The live grants of a user (not revoked, not expired, and with a live token: an account-wide
|
|
31
|
+
* invalidation removes them from this list), oldest first.
|
|
32
|
+
*/
|
|
33
|
+
list(user: unknown): Promise<OAuthGrant[]>;
|
|
34
|
+
/**
|
|
35
|
+
* Revokes one grant and its tokens. With `user`, only a grant of that user. True when it was
|
|
36
|
+
* live (not revoked before, not past its end).
|
|
37
|
+
*/
|
|
38
|
+
revoke(id: string, user?: unknown): Promise<boolean>;
|
|
39
|
+
/** Revokes every grant of a user and their tokens; the number of those that were live. */
|
|
40
|
+
revokeAll(user: unknown): Promise<number>;
|
|
41
|
+
/**
|
|
42
|
+
* Deletes expired and revoked grants, codes past their expiry (and a grace for replays) and
|
|
43
|
+
* registered clients unused for 30 days (sql and memory; redis expires them itself).
|
|
44
|
+
*/
|
|
45
|
+
purge(): Promise<{
|
|
46
|
+
grants: number;
|
|
47
|
+
codes: number;
|
|
48
|
+
clients: number;
|
|
49
|
+
}>;
|
|
50
|
+
}
|
|
51
|
+
/** Defaults of `grantTouchMs`, `codeGraceMs` and `clientUnusedMs` (D-0113 §5). */
|
|
52
|
+
export declare const GRANT_MAX_PER_CLIENT: 20;
|
|
53
|
+
export declare const GRANT_TOUCH_MS: 60000;
|
|
54
|
+
export declare const CODE_GRACE_MS: 600000;
|
|
55
|
+
export declare const CLIENT_UNUSED_MS: number;
|
|
56
|
+
/** The limits of `GrantService` (dokebi-oauth options, D-0113 §5). */
|
|
57
|
+
export interface GrantLimits {
|
|
58
|
+
readonly grantTouchMs: number;
|
|
59
|
+
readonly maxCachedGrants: number;
|
|
60
|
+
readonly codeGraceMs: number;
|
|
61
|
+
readonly clientUnusedMs: number;
|
|
62
|
+
/** `refreshMs`: a client is kept at least this long after its last use (`clientKeptMs`). */
|
|
63
|
+
readonly refreshMs: number;
|
|
64
|
+
readonly storeRetryAfterMs: number;
|
|
65
|
+
readonly storeFullRetryAfterMs: number;
|
|
66
|
+
readonly logRepeatWindowMs: number;
|
|
67
|
+
/** D-0124: live grants one user may hold for one client (`grant.maxPerClient`). */
|
|
68
|
+
readonly maxPerClient: number;
|
|
69
|
+
}
|
|
70
|
+
export declare function newGrantId(): string;
|
|
71
|
+
/** The public view of a stored grant. */
|
|
72
|
+
export declare function grantView(row: GrantRow): OAuthGrant;
|
|
73
|
+
/** Store calls with one failure rule, the grant cache and the last-use writes. */
|
|
74
|
+
export declare class GrantService implements OAuthGrants {
|
|
75
|
+
#private;
|
|
76
|
+
readonly store: OAuthStore;
|
|
77
|
+
readonly realm: string;
|
|
78
|
+
readonly repeats: InstanceType<typeof diagnostics.Repeats>;
|
|
79
|
+
/** D-0122: the open Bearer connections of this process; a revocation here ends them at once. */
|
|
80
|
+
readonly connections: LiveGrants;
|
|
81
|
+
constructor(settings: {
|
|
82
|
+
readonly store: OAuthStore;
|
|
83
|
+
readonly realm: string;
|
|
84
|
+
readonly auth: AuthRealmApi;
|
|
85
|
+
readonly logger: Logger;
|
|
86
|
+
readonly cacheMs: number;
|
|
87
|
+
/** dokebi.yaml limits (D-0113 §5); each missing one has its default. */
|
|
88
|
+
readonly limits?: Partial<GrantLimits>;
|
|
89
|
+
});
|
|
90
|
+
/** The store's retry hint of a full store (`storeFullRetryAfterMs`). */
|
|
91
|
+
get storeFullRetryAfterMs(): number;
|
|
92
|
+
/** Calls the store; failures become 503 STORE_FAILED with the cause (logged once in a while). */
|
|
93
|
+
call<T>(operation: string, work: () => Promise<T>): Promise<T>;
|
|
94
|
+
find(id: string): Promise<GrantRow | undefined>;
|
|
95
|
+
/** A grant for a protected request: the store, or the cache of `grantCacheMs`. */
|
|
96
|
+
cached(id: string, now: number): Promise<GrantRow | undefined>;
|
|
97
|
+
forget(id?: string): void;
|
|
98
|
+
/** Writes lastUsedAt at most once per `grantTouchMs` per grant, off the request path. */
|
|
99
|
+
touch(row: GrantRow, now: number): void;
|
|
100
|
+
/**
|
|
101
|
+
* D-0124: what this user allowed this client for this resource before: the newest live grant of
|
|
102
|
+
* them (the consent page offers its scopes, kind and binding again), or undefined.
|
|
103
|
+
*/
|
|
104
|
+
remembered(userId: string, clientId: string, resource: string, now: number): Promise<GrantRow | undefined>;
|
|
105
|
+
/**
|
|
106
|
+
* D-0124: room for one more grant of this user and client under `grant.maxPerClient`. Below it
|
|
107
|
+
* nothing is read but the user's grants. At it, the user's live token families are read once
|
|
108
|
+
* and grants are revoked until one fits: first those that never got a live token (a consent
|
|
109
|
+
* whose code was not exchanged within `codeMs`, or whose tokens all ended), oldest first; then
|
|
110
|
+
* the least recently used (`lastUsedAt`, else `createdAt`). A legitimate new device is never
|
|
111
|
+
* refused: an old one is signed out instead, logged at warn OAUTH_GRANT_EVICTED (once per client
|
|
112
|
+
* and `logRepeatWindowMs`, counted). Concurrent consents may pass the bound by their number.
|
|
113
|
+
*/
|
|
114
|
+
makeRoom(user: unknown, userId: string, clientId: string, now: number, codeMs: number): Promise<number>;
|
|
115
|
+
/** Revokes a grant row and its token family; true when the grant was live. */
|
|
116
|
+
revokeRow(row: GrantRow, reason: string): Promise<boolean>;
|
|
117
|
+
list(user: unknown): Promise<OAuthGrant[]>;
|
|
118
|
+
revoke(id: string, user?: unknown): Promise<boolean>;
|
|
119
|
+
revokeAll(user: unknown): Promise<number>;
|
|
120
|
+
purge(): Promise<{
|
|
121
|
+
grants: number;
|
|
122
|
+
codes: number;
|
|
123
|
+
clients: number;
|
|
124
|
+
}>;
|
|
125
|
+
flush(): void;
|
|
126
|
+
}
|
package/dist/grants.js
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { diagnostics } from '@dokebi/core/libraries';
|
|
3
|
+
import { OAuthError } from './errors.js';
|
|
4
|
+
import { LiveGrants } from './live.js';
|
|
5
|
+
import { LIMITS_DEFAULT } from './options.js';
|
|
6
|
+
import { clientKeptMs } from './store.js';
|
|
7
|
+
/** Defaults of `grantTouchMs`, `codeGraceMs` and `clientUnusedMs` (D-0113 §5). */
|
|
8
|
+
export const GRANT_MAX_PER_CLIENT = LIMITS_DEFAULT.maxPerClient;
|
|
9
|
+
export const GRANT_TOUCH_MS = LIMITS_DEFAULT.grantTouchMs;
|
|
10
|
+
export const CODE_GRACE_MS = LIMITS_DEFAULT.codeGraceMs;
|
|
11
|
+
export const CLIENT_UNUSED_MS = LIMITS_DEFAULT.clientUnusedMs;
|
|
12
|
+
const date = (value) => (value === null ? null : new Date(value));
|
|
13
|
+
const GRANT_LIMITS_DEFAULT = Object.freeze({
|
|
14
|
+
grantTouchMs: LIMITS_DEFAULT.grantTouchMs,
|
|
15
|
+
maxCachedGrants: LIMITS_DEFAULT.maxCachedGrants,
|
|
16
|
+
codeGraceMs: LIMITS_DEFAULT.codeGraceMs,
|
|
17
|
+
clientUnusedMs: LIMITS_DEFAULT.clientUnusedMs,
|
|
18
|
+
refreshMs: LIMITS_DEFAULT.refreshMs,
|
|
19
|
+
storeRetryAfterMs: LIMITS_DEFAULT.storeRetryAfterMs,
|
|
20
|
+
storeFullRetryAfterMs: LIMITS_DEFAULT.storeFullRetryAfterMs,
|
|
21
|
+
logRepeatWindowMs: LIMITS_DEFAULT.logRepeatWindowMs,
|
|
22
|
+
maxPerClient: LIMITS_DEFAULT.maxPerClient,
|
|
23
|
+
});
|
|
24
|
+
export function newGrantId() {
|
|
25
|
+
return randomBytes(16).toString('base64url');
|
|
26
|
+
}
|
|
27
|
+
/** The public view of a stored grant. */
|
|
28
|
+
export function grantView(row) {
|
|
29
|
+
let binding = null;
|
|
30
|
+
if (row.binding !== null)
|
|
31
|
+
binding = JSON.parse(row.binding);
|
|
32
|
+
return Object.freeze({
|
|
33
|
+
id: row.id,
|
|
34
|
+
realm: row.realm,
|
|
35
|
+
userId: row.userId,
|
|
36
|
+
clientId: row.clientId,
|
|
37
|
+
clientName: row.clientName,
|
|
38
|
+
resource: row.resource,
|
|
39
|
+
scopes: Object.freeze([...row.scopes]),
|
|
40
|
+
kind: row.kind,
|
|
41
|
+
binding,
|
|
42
|
+
createdAt: new Date(row.createdAt),
|
|
43
|
+
expiresAt: new Date(row.expiresAt),
|
|
44
|
+
lastUsedAt: date(row.lastUsedAt),
|
|
45
|
+
revokedAt: date(row.revokedAt),
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
/** Store calls with one failure rule, the grant cache and the last-use writes. */
|
|
49
|
+
export class GrantService {
|
|
50
|
+
store;
|
|
51
|
+
realm;
|
|
52
|
+
#auth;
|
|
53
|
+
#logger;
|
|
54
|
+
#cacheMs;
|
|
55
|
+
#limits;
|
|
56
|
+
#cache = new Map();
|
|
57
|
+
#touched = new Map();
|
|
58
|
+
repeats;
|
|
59
|
+
/** D-0122: the open Bearer connections of this process; a revocation here ends them at once. */
|
|
60
|
+
connections = new LiveGrants();
|
|
61
|
+
constructor(settings) {
|
|
62
|
+
this.store = settings.store;
|
|
63
|
+
this.realm = settings.realm;
|
|
64
|
+
this.#auth = settings.auth;
|
|
65
|
+
this.#logger = settings.logger;
|
|
66
|
+
this.#cacheMs = settings.cacheMs;
|
|
67
|
+
this.#limits = { ...GRANT_LIMITS_DEFAULT, ...settings.limits };
|
|
68
|
+
this.repeats = new diagnostics.Repeats({
|
|
69
|
+
logger: settings.logger,
|
|
70
|
+
intervalMs: this.#limits.logRepeatWindowMs,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/** The store's retry hint of a full store (`storeFullRetryAfterMs`). */
|
|
74
|
+
get storeFullRetryAfterMs() {
|
|
75
|
+
return this.#limits.storeFullRetryAfterMs;
|
|
76
|
+
}
|
|
77
|
+
/** Calls the store; failures become 503 STORE_FAILED with the cause (logged once in a while). */
|
|
78
|
+
async call(operation, work) {
|
|
79
|
+
try {
|
|
80
|
+
return await work();
|
|
81
|
+
}
|
|
82
|
+
catch (cause) {
|
|
83
|
+
if (cause instanceof OAuthError) {
|
|
84
|
+
if (cause.code === 'STORE_FULL')
|
|
85
|
+
this.repeats.log('warn', 'OAuth store full: a new grant or client was refused', 'OAUTH_STORE_FULL', undefined, { store: this.store.name, operation, ...cause.data }, `full\u0000${operation}`);
|
|
86
|
+
throw cause;
|
|
87
|
+
}
|
|
88
|
+
this.repeats.log('error', 'OAuth store failed', 'OAUTH_STORE_FAILED', cause, { store: this.store.name, operation }, operation);
|
|
89
|
+
throw new OAuthError('STORE_FAILED', 'The OAuth store did not answer', {
|
|
90
|
+
cause,
|
|
91
|
+
status: 503,
|
|
92
|
+
hint: 'Try again in a moment.',
|
|
93
|
+
// Retry-After (D-0109 §7): an outage is retried, never a 500.
|
|
94
|
+
data: { store: this.store.name, retryAfterMs: this.#limits.storeRetryAfterMs },
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
find(id) {
|
|
99
|
+
return this.call('findGrant', () => this.store.findGrant(id));
|
|
100
|
+
}
|
|
101
|
+
/** A grant for a protected request: the store, or the cache of `grantCacheMs`. */
|
|
102
|
+
async cached(id, now) {
|
|
103
|
+
if (this.#cacheMs > 0) {
|
|
104
|
+
const entry = this.#cache.get(id);
|
|
105
|
+
if (entry && entry.until > now)
|
|
106
|
+
return entry.row;
|
|
107
|
+
}
|
|
108
|
+
const row = await this.find(id);
|
|
109
|
+
if (this.#cacheMs > 0) {
|
|
110
|
+
if (this.#cache.size >= this.#limits.maxCachedGrants) {
|
|
111
|
+
const oldest = this.#cache.keys().next();
|
|
112
|
+
if (!oldest.done)
|
|
113
|
+
this.#cache.delete(oldest.value);
|
|
114
|
+
}
|
|
115
|
+
this.#cache.set(id, { row, until: now + this.#cacheMs });
|
|
116
|
+
}
|
|
117
|
+
return row;
|
|
118
|
+
}
|
|
119
|
+
forget(id) {
|
|
120
|
+
if (id === undefined)
|
|
121
|
+
this.#cache.clear();
|
|
122
|
+
else
|
|
123
|
+
this.#cache.delete(id);
|
|
124
|
+
}
|
|
125
|
+
/** Writes lastUsedAt at most once per `grantTouchMs` per grant, off the request path. */
|
|
126
|
+
touch(row, now) {
|
|
127
|
+
const last = Math.max(row.lastUsedAt ?? 0, this.#touched.get(row.id) ?? 0);
|
|
128
|
+
if (now - last < this.#limits.grantTouchMs)
|
|
129
|
+
return;
|
|
130
|
+
// Bounded by maxCachedGrants: the oldest memo makes room (never all at once, which would
|
|
131
|
+
// write every busy grant again).
|
|
132
|
+
this.#touched.delete(row.id);
|
|
133
|
+
if (this.#touched.size >= this.#limits.maxCachedGrants) {
|
|
134
|
+
const oldest = this.#touched.keys().next();
|
|
135
|
+
if (!oldest.done)
|
|
136
|
+
this.#touched.delete(oldest.value);
|
|
137
|
+
}
|
|
138
|
+
this.#touched.set(row.id, now);
|
|
139
|
+
this.store.touchGrant(row.id, now).then(undefined, (error) => this.repeats.log('error', 'OAuth grant last use not written', 'OAUTH_TOUCH_FAILED', error, {
|
|
140
|
+
store: this.store.name,
|
|
141
|
+
}));
|
|
142
|
+
}
|
|
143
|
+
/** The live grants of a user for one client (every resource). */
|
|
144
|
+
async #ofClient(userId, clientId, now) {
|
|
145
|
+
const rows = await this.call('listGrants', () => this.store.listGrants(this.realm, userId));
|
|
146
|
+
return rows.filter((row) => row.realm === this.realm &&
|
|
147
|
+
row.userId === userId &&
|
|
148
|
+
row.clientId === clientId &&
|
|
149
|
+
row.revokedAt === null &&
|
|
150
|
+
row.expiresAt > now);
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* D-0124: what this user allowed this client for this resource before: the newest live grant of
|
|
154
|
+
* them (the consent page offers its scopes, kind and binding again), or undefined.
|
|
155
|
+
*/
|
|
156
|
+
async remembered(userId, clientId, resource, now) {
|
|
157
|
+
let newest;
|
|
158
|
+
for (const row of await this.#ofClient(userId, clientId, now))
|
|
159
|
+
if (row.resource === resource && (!newest || row.createdAt > newest.createdAt))
|
|
160
|
+
newest = row;
|
|
161
|
+
return newest;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* D-0124: room for one more grant of this user and client under `grant.maxPerClient`. Below it
|
|
165
|
+
* nothing is read but the user's grants. At it, the user's live token families are read once
|
|
166
|
+
* and grants are revoked until one fits: first those that never got a live token (a consent
|
|
167
|
+
* whose code was not exchanged within `codeMs`, or whose tokens all ended), oldest first; then
|
|
168
|
+
* the least recently used (`lastUsedAt`, else `createdAt`). A legitimate new device is never
|
|
169
|
+
* refused: an old one is signed out instead, logged at warn OAUTH_GRANT_EVICTED (once per client
|
|
170
|
+
* and `logRepeatWindowMs`, counted). Concurrent consents may pass the bound by their number.
|
|
171
|
+
*/
|
|
172
|
+
async makeRoom(user, userId, clientId, now, codeMs) {
|
|
173
|
+
const max = this.#limits.maxPerClient;
|
|
174
|
+
const rows = await this.#ofClient(userId, clientId, now);
|
|
175
|
+
if (rows.length < max)
|
|
176
|
+
return 0;
|
|
177
|
+
const families = new Set((await this.#auth.tokens.list(user))
|
|
178
|
+
.filter((token) => token.audience !== null && token.family !== null)
|
|
179
|
+
.map((token) => token.family));
|
|
180
|
+
const unused = (row) => !families.has(row.id) && row.createdAt + codeMs <= now;
|
|
181
|
+
const order = [...rows].sort((a, b) => {
|
|
182
|
+
const idle = Number(unused(b)) - Number(unused(a));
|
|
183
|
+
if (idle !== 0)
|
|
184
|
+
return idle;
|
|
185
|
+
return ((a.lastUsedAt ?? a.createdAt) - (b.lastUsedAt ?? b.createdAt) || a.createdAt - b.createdAt);
|
|
186
|
+
});
|
|
187
|
+
let evicted = 0;
|
|
188
|
+
for (const row of order.slice(0, rows.length - max + 1)) {
|
|
189
|
+
const used = !unused(row);
|
|
190
|
+
if (await this.revokeRow(row, used ? 'evicted' : 'unused'))
|
|
191
|
+
evicted++;
|
|
192
|
+
if (used)
|
|
193
|
+
this.repeats.log('warn', 'OAuth grant evicted: the user and client reached grant.maxPerClient', 'OAUTH_GRANT_EVICTED', undefined, { realm: row.realm, userId, clientId, grant: row.id, max }, `evicted\u0000${clientId}`);
|
|
194
|
+
}
|
|
195
|
+
diagnostics.logDebug(this.#logger, 'OAuth grants made room', () => ({
|
|
196
|
+
clientId,
|
|
197
|
+
live: rows.length,
|
|
198
|
+
max,
|
|
199
|
+
evicted,
|
|
200
|
+
}));
|
|
201
|
+
return evicted;
|
|
202
|
+
}
|
|
203
|
+
/** Revokes a grant row and its token family; true when the grant was live. */
|
|
204
|
+
async revokeRow(row, reason) {
|
|
205
|
+
const now = Date.now();
|
|
206
|
+
const revoked = await this.call('revokeGrant', () => this.store.revokeGrant(row.id, now));
|
|
207
|
+
const tokens = await this.#auth.tokens.revokeFamily(row.id);
|
|
208
|
+
this.forget(row.id);
|
|
209
|
+
const connections = this.connections.end(row.id);
|
|
210
|
+
if (revoked || tokens > 0)
|
|
211
|
+
this.#logger.log('info', 'OAuth grant revoked', {
|
|
212
|
+
code: 'OAUTH_GRANT_REVOKED',
|
|
213
|
+
realm: row.realm,
|
|
214
|
+
userId: row.userId,
|
|
215
|
+
clientId: row.clientId,
|
|
216
|
+
grant: row.id,
|
|
217
|
+
reason,
|
|
218
|
+
tokens,
|
|
219
|
+
...(connections ? { connections } : {}),
|
|
220
|
+
});
|
|
221
|
+
// Live: not revoked before and not past its end (an expired grant is marked, not counted).
|
|
222
|
+
return revoked && row.expiresAt > now;
|
|
223
|
+
}
|
|
224
|
+
#userId(user) {
|
|
225
|
+
if (user === null || typeof user !== 'object')
|
|
226
|
+
throw new OAuthError('INVALID_ARGUMENT', 'Grant calls need the user object', {
|
|
227
|
+
fix: 'Pass the row request.auth.user() (or findById) returns, not an id.',
|
|
228
|
+
});
|
|
229
|
+
return this.#auth.idOf(user);
|
|
230
|
+
}
|
|
231
|
+
async list(user) {
|
|
232
|
+
const userId = this.#userId(user);
|
|
233
|
+
const now = Date.now();
|
|
234
|
+
const rows = await this.call('listGrants', () => this.store.listGrants(this.realm, userId));
|
|
235
|
+
// The families that still have a live token for this user's current stamp.
|
|
236
|
+
const families = new Set((await this.#auth.tokens.list(user))
|
|
237
|
+
.filter((token) => token.audience !== null && token.family !== null)
|
|
238
|
+
.map((token) => token.family));
|
|
239
|
+
return rows
|
|
240
|
+
.filter((row) => row.realm === this.realm &&
|
|
241
|
+
row.userId === userId &&
|
|
242
|
+
row.revokedAt === null &&
|
|
243
|
+
row.expiresAt > now &&
|
|
244
|
+
families.has(row.id))
|
|
245
|
+
.sort((a, b) => a.createdAt - b.createdAt)
|
|
246
|
+
.map(grantView);
|
|
247
|
+
}
|
|
248
|
+
async revoke(id, user) {
|
|
249
|
+
if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{22}$/.test(id))
|
|
250
|
+
return false;
|
|
251
|
+
const owner = user === undefined ? undefined : this.#userId(user);
|
|
252
|
+
const row = await this.find(id);
|
|
253
|
+
if (!row || row.realm !== this.realm)
|
|
254
|
+
return false;
|
|
255
|
+
if (owner !== undefined && row.userId !== owner)
|
|
256
|
+
return false;
|
|
257
|
+
return this.revokeRow(row, 'api');
|
|
258
|
+
}
|
|
259
|
+
async revokeAll(user) {
|
|
260
|
+
const userId = this.#userId(user);
|
|
261
|
+
const rows = await this.call('listGrants', () => this.store.listGrants(this.realm, userId));
|
|
262
|
+
let count = 0;
|
|
263
|
+
for (const row of rows)
|
|
264
|
+
if (row.realm === this.realm && row.revokedAt === null && (await this.revokeRow(row, 'api')))
|
|
265
|
+
count++;
|
|
266
|
+
return count;
|
|
267
|
+
}
|
|
268
|
+
async purge() {
|
|
269
|
+
const counts = await this.call('purge', () => this.store.purge({
|
|
270
|
+
now: Date.now(),
|
|
271
|
+
codeGraceMs: this.#limits.codeGraceMs,
|
|
272
|
+
clientUnusedMs: clientKeptMs(this.#limits.clientUnusedMs, this.#limits.refreshMs),
|
|
273
|
+
}));
|
|
274
|
+
diagnostics.logDebug(this.#logger, 'OAuth store purged', { ...counts });
|
|
275
|
+
return { ...counts };
|
|
276
|
+
}
|
|
277
|
+
flush() {
|
|
278
|
+
this.repeats.flush();
|
|
279
|
+
}
|
|
280
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { OAuthRouteSetting, RequestOAuth } from './plugin.js';
|
|
2
|
+
export { type CimdFetch, type CimdResponse, isPublicAddress, } from './cimd.js';
|
|
3
|
+
/** Use with `context.getDependency(dependency)`; a registered `dokebi-oauth` is reused. */
|
|
4
|
+
export { dependency, provider } from './dependency.js';
|
|
5
|
+
export type { OAuthErrorCode, OAuthProtocolErrorCode } from './errors.js';
|
|
6
|
+
export { OAuthError } from './errors.js';
|
|
7
|
+
/**
|
|
8
|
+
* The extension base (D-0064): `export default class AppOAuth extends OAuthExtension<UserRow> {}`
|
|
9
|
+
* in src/infra/oauth/extension.ts. Hooks: dependencies, renderConsent (required), canDelegate,
|
|
10
|
+
* clientName, scopeLabel.
|
|
11
|
+
*/
|
|
12
|
+
export { type OAuthAcceptedDecision, type OAuthClientInfo, type OAuthClientKind, type OAuthConsent, type OAuthDecision, OAuthExtension, type OAuthHookContext, } from './extension.js';
|
|
13
|
+
export type { OAuthGrant, OAuthGrants } from './grants.js';
|
|
14
|
+
/** `api.live(request)`: `identity.authorization` of a Bearer SSE stream or WebSocket (D-0122). */
|
|
15
|
+
export type { OAuthLiveAuthorization } from './live.js';
|
|
16
|
+
export type { MemoryOAuthStoreOptions, OAuthCimdOptions, OAuthClientOptions, OAuthOptions, OAuthPaths, OAuthResourceOptions, OAuthStoreOptions, RedisOAuthStoreOptions, SqlOAuthStoreOptions, } from './options.js';
|
|
17
|
+
/** The options declaration (D-0063): `options.parse(input)`, `options.schema`. */
|
|
18
|
+
export { options } from './options.js';
|
|
19
|
+
export type { OAuthApi, OAuthEntry, OAuthPluginSettings, OAuthResourceInfo, OAuthRouteSetting, RequestOAuth, } from './plugin.js';
|
|
20
|
+
/**
|
|
21
|
+
* Factory input: `{ app, options?, entry }`; `entry` is the module of
|
|
22
|
+
* src/infra/oauth/extension.ts. Routes with `config.oauth` are protected resources.
|
|
23
|
+
*/
|
|
24
|
+
export { createPlugin, defineOAuthPlugin } from './plugin.js';
|
|
25
|
+
/** The one resource comparison and the redirect URI rule, for tools and tests. */
|
|
26
|
+
export { redirectMatches, resourceKey, sameResource } from './protocol.js';
|
|
27
|
+
export type { ClientRow, CodeRow, ConsumedCode, GrantRow, OAuthStore, PurgeCounts, PurgeSettings, } from './store.js';
|
|
28
|
+
export { MemoryOAuthStore } from './store.js';
|
|
29
|
+
/** The SQL tables: the statements the migration runs, per dialect (no DDL at start). */
|
|
30
|
+
export { dropOAuthTableStatements, oauthTableStatements, type SqlDialect, } from './store-sql.js';
|
|
31
|
+
declare module 'fastify' {
|
|
32
|
+
interface FastifyRequest {
|
|
33
|
+
/**
|
|
34
|
+
* The grant of a protected request (dokebi-oauth): `grant`, `resource`, `has(scope)`. On
|
|
35
|
+
* routes without `config.oauth`, `grant` is undefined.
|
|
36
|
+
*/
|
|
37
|
+
readonly oauth: RequestOAuth;
|
|
38
|
+
}
|
|
39
|
+
interface FastifyContextConfig {
|
|
40
|
+
/**
|
|
41
|
+
* A protected resource route (dokebi-oauth): `{ resource, scopes?, maxAge? }`. Requests need a
|
|
42
|
+
* Bearer token issued for that resource, of a live grant holding `scopes` (and with `maxAge`, a
|
|
43
|
+
* sign-in at most that many seconds old); otherwise 401/403 with
|
|
44
|
+
* `WWW-Authenticate: Bearer resource_metadata="…"`.
|
|
45
|
+
*/
|
|
46
|
+
oauth?: OAuthRouteSetting;
|
|
47
|
+
}
|
|
48
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* @dokebi/oauth (D-0091): an OAuth 2.1 authorization server on @dokebi/auth's opaque tokens —
|
|
3
|
+
* authorization code with PKCE S256, refresh rotation with reuse detection, revocation,
|
|
4
|
+
* authorization server and protected resource metadata, client ID metadata documents,
|
|
5
|
+
* pre-registered and (optionally) dynamically registered clients, and `config.oauth` routes.
|
|
6
|
+
*/
|
|
7
|
+
export { isPublicAddress, } from './cimd.js';
|
|
8
|
+
/** Use with `context.getDependency(dependency)`; a registered `dokebi-oauth` is reused. */
|
|
9
|
+
export { dependency, provider } from './dependency.js';
|
|
10
|
+
export { OAuthError } from './errors.js';
|
|
11
|
+
/**
|
|
12
|
+
* The extension base (D-0064): `export default class AppOAuth extends OAuthExtension<UserRow> {}`
|
|
13
|
+
* in src/infra/oauth/extension.ts. Hooks: dependencies, renderConsent (required), canDelegate,
|
|
14
|
+
* clientName, scopeLabel.
|
|
15
|
+
*/
|
|
16
|
+
export { OAuthExtension, } from './extension.js';
|
|
17
|
+
/** The options declaration (D-0063): `options.parse(input)`, `options.schema`. */
|
|
18
|
+
export { options } from './options.js';
|
|
19
|
+
/**
|
|
20
|
+
* Factory input: `{ app, options?, entry }`; `entry` is the module of
|
|
21
|
+
* src/infra/oauth/extension.ts. Routes with `config.oauth` are protected resources.
|
|
22
|
+
*/
|
|
23
|
+
export { createPlugin, defineOAuthPlugin } from './plugin.js';
|
|
24
|
+
/** The one resource comparison and the redirect URI rule, for tools and tests. */
|
|
25
|
+
export { redirectMatches, resourceKey, sameResource } from './protocol.js';
|
|
26
|
+
export { MemoryOAuthStore } from './store.js';
|
|
27
|
+
/** The SQL tables: the statements the migration runs, per dialect (no DDL at start). */
|
|
28
|
+
export { dropOAuthTableStatements, oauthTableStatements, } from './store-sql.js';
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
interface InstallContext {
|
|
2
|
+
readonly options: Readonly<Record<string, unknown>>;
|
|
3
|
+
}
|
|
4
|
+
interface Diagnostic {
|
|
5
|
+
readonly code: string;
|
|
6
|
+
readonly severity: 'error' | 'warning';
|
|
7
|
+
readonly optionPath?: readonly string[];
|
|
8
|
+
readonly hint?: string;
|
|
9
|
+
}
|
|
10
|
+
export declare function planInstall(context: InstallContext): {
|
|
11
|
+
requires: string[];
|
|
12
|
+
entry: {
|
|
13
|
+
source: string;
|
|
14
|
+
target: string;
|
|
15
|
+
};
|
|
16
|
+
files?: {
|
|
17
|
+
source: string;
|
|
18
|
+
target: string;
|
|
19
|
+
}[];
|
|
20
|
+
};
|
|
21
|
+
/** An existing entry file is never replaced. */
|
|
22
|
+
export declare function planUpgrade(context: InstallContext): {
|
|
23
|
+
requires: string[];
|
|
24
|
+
entry: {
|
|
25
|
+
source: string;
|
|
26
|
+
target: string;
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
export declare function check(context: InstallContext): {
|
|
30
|
+
requires: string[];
|
|
31
|
+
diagnostics: Diagnostic[];
|
|
32
|
+
};
|
|
33
|
+
export {};
|