@20baht/elysia-oauth-provider 0.0.0-stage → 0.2.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.
Files changed (62) hide show
  1. package/README.md +655 -2
  2. package/dist/config.d.ts +37 -0
  3. package/dist/config.d.ts.map +1 -0
  4. package/dist/core/bearer.d.ts +11 -0
  5. package/dist/core/bearer.d.ts.map +1 -0
  6. package/dist/core/pkce.d.ts +6 -0
  7. package/dist/core/pkce.d.ts.map +1 -0
  8. package/dist/core/provider.d.ts +109 -0
  9. package/dist/core/provider.d.ts.map +1 -0
  10. package/dist/core/rate-limit.d.ts +61 -0
  11. package/dist/core/rate-limit.d.ts.map +1 -0
  12. package/dist/core/redirect-uri.d.ts +19 -0
  13. package/dist/core/redirect-uri.d.ts.map +1 -0
  14. package/dist/core/resource.d.ts +19 -0
  15. package/dist/core/resource.d.ts.map +1 -0
  16. package/dist/core/scope.d.ts +7 -0
  17. package/dist/core/scope.d.ts.map +1 -0
  18. package/dist/crypto/hash.d.ts +10 -0
  19. package/dist/crypto/hash.d.ts.map +1 -0
  20. package/dist/crypto/jwt.d.ts +51 -0
  21. package/dist/crypto/jwt.d.ts.map +1 -0
  22. package/dist/crypto/props-encryption.d.ts +14 -0
  23. package/dist/crypto/props-encryption.d.ts.map +1 -0
  24. package/dist/crypto/random.d.ts +8 -0
  25. package/dist/crypto/random.d.ts.map +1 -0
  26. package/dist/endpoints/authorize.d.ts +4 -0
  27. package/dist/endpoints/authorize.d.ts.map +1 -0
  28. package/dist/endpoints/http.d.ts +27 -0
  29. package/dist/endpoints/http.d.ts.map +1 -0
  30. package/dist/endpoints/metadata.d.ts +9 -0
  31. package/dist/endpoints/metadata.d.ts.map +1 -0
  32. package/dist/endpoints/register.d.ts +4 -0
  33. package/dist/endpoints/register.d.ts.map +1 -0
  34. package/dist/endpoints/revoke.d.ts +4 -0
  35. package/dist/endpoints/revoke.d.ts.map +1 -0
  36. package/dist/endpoints/token.d.ts +4 -0
  37. package/dist/endpoints/token.d.ts.map +1 -0
  38. package/dist/errors.d.ts +42 -0
  39. package/dist/errors.d.ts.map +1 -0
  40. package/dist/index.d.ts +28 -0
  41. package/dist/index.d.ts.map +1 -0
  42. package/dist/index.js +2376 -0
  43. package/dist/index.js.map +33 -0
  44. package/dist/plugin.d.ts +426 -0
  45. package/dist/plugin.d.ts.map +1 -0
  46. package/dist/storage/conformance.d.ts +36 -0
  47. package/dist/storage/conformance.d.ts.map +1 -0
  48. package/dist/storage/conformance.js +163 -0
  49. package/dist/storage/conformance.js.map +10 -0
  50. package/dist/storage/keys.d.ts +33 -0
  51. package/dist/storage/keys.d.ts.map +1 -0
  52. package/dist/storage/memory.d.ts +35 -0
  53. package/dist/storage/memory.d.ts.map +1 -0
  54. package/dist/storage/redis.d.ts +83 -0
  55. package/dist/storage/redis.d.ts.map +1 -0
  56. package/dist/storage/redis.js +135 -0
  57. package/dist/storage/redis.js.map +10 -0
  58. package/dist/storage/types.d.ts +61 -0
  59. package/dist/storage/types.d.ts.map +1 -0
  60. package/dist/types.d.ts +329 -0
  61. package/dist/types.d.ts.map +1 -0
  62. package/package.json +67 -4
@@ -0,0 +1,426 @@
1
+ import { Elysia } from 'elysia';
2
+ import { OAuthProviderCore, type CreateClientInput } from './core/provider.js';
3
+ import type { AuthRequest, ClientInfo, CompleteAuthorizationOptions, GrantSummary, OAuthContext, OAuthProviderConfig, PendingAuthRequest, RejectAuthorizationOptions, TokenInfo } from './types.js';
4
+ /** Helpers exposed as `ctx.oauthProvider` inside handlers (and as `plugin.decorator.oauthProvider`). */
5
+ export interface OAuthHelpers<Props> {
6
+ /** Validate `/authorize` query params yourself (workers-oauth-provider style). */
7
+ parseAuthRequest(url: URL | string | Request): Promise<{
8
+ authRequest: AuthRequest;
9
+ client: ClientInfo;
10
+ }>;
11
+ /** Load a pending request stashed by `GET /authorize`. */
12
+ getAuthRequest(authRequestId: string): Promise<PendingAuthRequest | null>;
13
+ /** Issue an authorization code and return where to redirect the user-agent. */
14
+ completeAuthorization(options: CompleteAuthorizationOptions<Props>): Promise<{
15
+ redirectTo: string;
16
+ }>;
17
+ /** Send the user-agent back to the client with an error (e.g. consent denied). */
18
+ rejectAuthorization(options: RejectAuthorizationOptions): Promise<{
19
+ redirectTo: string;
20
+ }>;
21
+ /** Verify a bearer token string. `null` when invalid / expired / revoked. */
22
+ verifyAccessToken(token: string, requestUrl?: string): Promise<TokenInfo<Props> | null>;
23
+ createClient(input: CreateClientInput): Promise<ClientInfo>;
24
+ lookupClient(clientId: string): Promise<ClientInfo | null>;
25
+ updateClient(clientId: string, updates: Partial<Omit<CreateClientInput, 'clientId' | 'dynamicallyRegistered'>>): Promise<ClientInfo | null>;
26
+ deleteClient(clientId: string): Promise<void>;
27
+ listClients(): Promise<ClientInfo[]>;
28
+ listUserGrants(userId: string): Promise<GrantSummary[]>;
29
+ /** Every live grant (all users and clients). */
30
+ listGrants(): Promise<GrantSummary[]>;
31
+ listClientGrants(clientId: string): Promise<GrantSummary[]>;
32
+ revokeGrant(grantId: string, userId: string): Promise<void>;
33
+ /** Escape hatch to the engine. */
34
+ readonly core: OAuthProviderCore<Props>;
35
+ }
36
+ export interface OAuthMacroOptions {
37
+ /** Every listed scope must be present on the token (403 `insufficient_scope` otherwise). */
38
+ scopes?: string[];
39
+ }
40
+ /**
41
+ * OAuth 2.1 authorization server as an Elysia plugin.
42
+ *
43
+ * ```ts
44
+ * const app = new Elysia()
45
+ * .use(oauthProvider<Props>({ issuer, storage, handleAuthorize }))
46
+ * .post('/mcp', ({ oauth }) => oauth.props, { oauth: { scopes: ['mcp'] } })
47
+ * ```
48
+ */
49
+ export declare function oauthProvider<Props = Record<string, unknown>>(userConfig: OAuthProviderConfig<Props>): Elysia<"", {
50
+ decorator: {
51
+ oauthProvider: OAuthHelpers<Props>;
52
+ };
53
+ store: {};
54
+ derive: {};
55
+ resolve: {};
56
+ }, {
57
+ typebox: {};
58
+ error: {};
59
+ }, {
60
+ schema: {};
61
+ standaloneSchema: {};
62
+ macro: Partial<{
63
+ readonly oauth: true | OAuthMacroOptions;
64
+ }>;
65
+ macroFn: {
66
+ readonly oauth: (options: true | OAuthMacroOptions) => {
67
+ readonly resolve: ({ request, set, status }: {
68
+ body: unknown;
69
+ query: Record<string, string>;
70
+ params: {};
71
+ headers: Record<string, string | undefined>;
72
+ cookie: Record<string, import("elysia").Cookie<unknown>>;
73
+ server: import("elysia/universal/server").Server | null;
74
+ redirect: import("elysia").redirect;
75
+ set: {
76
+ headers: import("elysia").HTTPHeaders;
77
+ status?: number | keyof import("elysia").StatusMap;
78
+ redirect?: string;
79
+ cookie?: Record<string, import("elysia/cookies").ElysiaCookie>;
80
+ };
81
+ path: string;
82
+ route: string;
83
+ request: Request;
84
+ store: {};
85
+ status: <const Code extends number | keyof import("elysia").StatusMap, const T = Code extends 401 | 403 | 500 | 503 | 400 | 302 | 200 | 405 | 413 | 201 | 204 | 100 | 101 | 102 | 103 | 202 | 203 | 205 | 206 | 207 | 208 | 300 | 301 | 303 | 304 | 307 | 308 | 402 | 404 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 414 | 415 | 416 | 417 | 418 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 428 | 429 | 431 | 451 | 501 | 502 | 504 | 505 | 506 | 507 | 508 | 510 | 511 ? {
86
+ readonly 100: "Continue";
87
+ readonly 101: "Switching Protocols";
88
+ readonly 102: "Processing";
89
+ readonly 103: "Early Hints";
90
+ readonly 200: "OK";
91
+ readonly 201: "Created";
92
+ readonly 202: "Accepted";
93
+ readonly 203: "Non-Authoritative Information";
94
+ readonly 204: "No Content";
95
+ readonly 205: "Reset Content";
96
+ readonly 206: "Partial Content";
97
+ readonly 207: "Multi-Status";
98
+ readonly 208: "Already Reported";
99
+ readonly 300: "Multiple Choices";
100
+ readonly 301: "Moved Permanently";
101
+ readonly 302: "Found";
102
+ readonly 303: "See Other";
103
+ readonly 304: "Not Modified";
104
+ readonly 307: "Temporary Redirect";
105
+ readonly 308: "Permanent Redirect";
106
+ readonly 400: "Bad Request";
107
+ readonly 401: "Unauthorized";
108
+ readonly 402: "Payment Required";
109
+ readonly 403: "Forbidden";
110
+ readonly 404: "Not Found";
111
+ readonly 405: "Method Not Allowed";
112
+ readonly 406: "Not Acceptable";
113
+ readonly 407: "Proxy Authentication Required";
114
+ readonly 408: "Request Timeout";
115
+ readonly 409: "Conflict";
116
+ readonly 410: "Gone";
117
+ readonly 411: "Length Required";
118
+ readonly 412: "Precondition Failed";
119
+ readonly 413: "Payload Too Large";
120
+ readonly 414: "URI Too Long";
121
+ readonly 415: "Unsupported Media Type";
122
+ readonly 416: "Range Not Satisfiable";
123
+ readonly 417: "Expectation Failed";
124
+ readonly 418: "I'm a teapot";
125
+ readonly 420: "Enhance Your Calm";
126
+ readonly 421: "Misdirected Request";
127
+ readonly 422: "Unprocessable Content";
128
+ readonly 423: "Locked";
129
+ readonly 424: "Failed Dependency";
130
+ readonly 425: "Too Early";
131
+ readonly 426: "Upgrade Required";
132
+ readonly 428: "Precondition Required";
133
+ readonly 429: "Too Many Requests";
134
+ readonly 431: "Request Header Fields Too Large";
135
+ readonly 451: "Unavailable For Legal Reasons";
136
+ readonly 500: "Internal Server Error";
137
+ readonly 501: "Not Implemented";
138
+ readonly 502: "Bad Gateway";
139
+ readonly 503: "Service Unavailable";
140
+ readonly 504: "Gateway Timeout";
141
+ readonly 505: "HTTP Version Not Supported";
142
+ readonly 506: "Variant Also Negotiates";
143
+ readonly 507: "Insufficient Storage";
144
+ readonly 508: "Loop Detected";
145
+ readonly 510: "Not Extended";
146
+ readonly 511: "Network Authentication Required";
147
+ }[Code] : Code>(code: Code, response?: T) => import("elysia").ElysiaCustomStatusResponse<Code, T, Code extends "Continue" | "Switching Protocols" | "Processing" | "Early Hints" | "OK" | "Created" | "Accepted" | "Non-Authoritative Information" | "No Content" | "Reset Content" | "Partial Content" | "Multi-Status" | "Already Reported" | "Multiple Choices" | "Moved Permanently" | "Found" | "See Other" | "Not Modified" | "Temporary Redirect" | "Permanent Redirect" | "Bad Request" | "Unauthorized" | "Payment Required" | "Forbidden" | "Not Found" | "Method Not Allowed" | "Not Acceptable" | "Proxy Authentication Required" | "Request Timeout" | "Conflict" | "Gone" | "Length Required" | "Precondition Failed" | "Payload Too Large" | "URI Too Long" | "Unsupported Media Type" | "Range Not Satisfiable" | "Expectation Failed" | "I'm a teapot" | "Enhance Your Calm" | "Misdirected Request" | "Unprocessable Content" | "Locked" | "Failed Dependency" | "Too Early" | "Upgrade Required" | "Precondition Required" | "Too Many Requests" | "Request Header Fields Too Large" | "Unavailable For Legal Reasons" | "Internal Server Error" | "Not Implemented" | "Bad Gateway" | "Service Unavailable" | "Gateway Timeout" | "HTTP Version Not Supported" | "Variant Also Negotiates" | "Insufficient Storage" | "Loop Detected" | "Not Extended" | "Network Authentication Required" ? {
148
+ readonly Continue: 100;
149
+ readonly "Switching Protocols": 101;
150
+ readonly Processing: 102;
151
+ readonly "Early Hints": 103;
152
+ readonly OK: 200;
153
+ readonly Created: 201;
154
+ readonly Accepted: 202;
155
+ readonly "Non-Authoritative Information": 203;
156
+ readonly "No Content": 204;
157
+ readonly "Reset Content": 205;
158
+ readonly "Partial Content": 206;
159
+ readonly "Multi-Status": 207;
160
+ readonly "Already Reported": 208;
161
+ readonly "Multiple Choices": 300;
162
+ readonly "Moved Permanently": 301;
163
+ readonly Found: 302;
164
+ readonly "See Other": 303;
165
+ readonly "Not Modified": 304;
166
+ readonly "Temporary Redirect": 307;
167
+ readonly "Permanent Redirect": 308;
168
+ readonly "Bad Request": 400;
169
+ readonly Unauthorized: 401;
170
+ readonly "Payment Required": 402;
171
+ readonly Forbidden: 403;
172
+ readonly "Not Found": 404;
173
+ readonly "Method Not Allowed": 405;
174
+ readonly "Not Acceptable": 406;
175
+ readonly "Proxy Authentication Required": 407;
176
+ readonly "Request Timeout": 408;
177
+ readonly Conflict: 409;
178
+ readonly Gone: 410;
179
+ readonly "Length Required": 411;
180
+ readonly "Precondition Failed": 412;
181
+ readonly "Payload Too Large": 413;
182
+ readonly "URI Too Long": 414;
183
+ readonly "Unsupported Media Type": 415;
184
+ readonly "Range Not Satisfiable": 416;
185
+ readonly "Expectation Failed": 417;
186
+ readonly "I'm a teapot": 418;
187
+ readonly "Enhance Your Calm": 420;
188
+ readonly "Misdirected Request": 421;
189
+ readonly "Unprocessable Content": 422;
190
+ readonly Locked: 423;
191
+ readonly "Failed Dependency": 424;
192
+ readonly "Too Early": 425;
193
+ readonly "Upgrade Required": 426;
194
+ readonly "Precondition Required": 428;
195
+ readonly "Too Many Requests": 429;
196
+ readonly "Request Header Fields Too Large": 431;
197
+ readonly "Unavailable For Legal Reasons": 451;
198
+ readonly "Internal Server Error": 500;
199
+ readonly "Not Implemented": 501;
200
+ readonly "Bad Gateway": 502;
201
+ readonly "Service Unavailable": 503;
202
+ readonly "Gateway Timeout": 504;
203
+ readonly "HTTP Version Not Supported": 505;
204
+ readonly "Variant Also Negotiates": 506;
205
+ readonly "Insufficient Storage": 507;
206
+ readonly "Loop Detected": 508;
207
+ readonly "Not Extended": 510;
208
+ readonly "Network Authentication Required": 511;
209
+ }[Code] : Code>;
210
+ oauthProvider: OAuthHelpers<Props>;
211
+ }) => Promise<import("elysia").ElysiaCustomStatusResponse<401 | 403, "" | Record<string, string>, 401 | 403> | {
212
+ oauth: OAuthContext<Props>;
213
+ }>;
214
+ };
215
+ };
216
+ parser: {};
217
+ response: {};
218
+ }, {
219
+ ".well-known": {
220
+ "oauth-authorization-server": {
221
+ get: {
222
+ body: unknown;
223
+ params: {};
224
+ query: unknown;
225
+ headers: unknown;
226
+ response: {
227
+ 200: Response;
228
+ };
229
+ };
230
+ };
231
+ };
232
+ } & {
233
+ ".well-known": {
234
+ "oauth-authorization-server": {
235
+ options: {
236
+ body: unknown;
237
+ params: {};
238
+ query: unknown;
239
+ headers: unknown;
240
+ response: {
241
+ 200: Response;
242
+ };
243
+ };
244
+ };
245
+ };
246
+ } & {
247
+ ".well-known": {
248
+ "oauth-protected-resource": {
249
+ get: {
250
+ body: unknown;
251
+ params: {};
252
+ query: unknown;
253
+ headers: unknown;
254
+ response: {
255
+ 200: Response;
256
+ };
257
+ };
258
+ };
259
+ };
260
+ } & {
261
+ ".well-known": {
262
+ "oauth-protected-resource": {
263
+ options: {
264
+ body: unknown;
265
+ params: {};
266
+ query: unknown;
267
+ headers: unknown;
268
+ response: {
269
+ 200: Response;
270
+ };
271
+ };
272
+ };
273
+ };
274
+ } & {
275
+ ".well-known": {
276
+ "oauth-protected-resource": {
277
+ "*": {
278
+ get: {
279
+ body: unknown;
280
+ params: {
281
+ "*": string;
282
+ } & {};
283
+ query: unknown;
284
+ headers: unknown;
285
+ response: {
286
+ 200: Response;
287
+ 422: {
288
+ type: "validation";
289
+ on: string;
290
+ summary?: string;
291
+ message?: string;
292
+ found?: unknown;
293
+ property?: string;
294
+ expected?: string;
295
+ };
296
+ };
297
+ };
298
+ };
299
+ };
300
+ };
301
+ } & {
302
+ ".well-known": {
303
+ "oauth-protected-resource": {
304
+ "*": {
305
+ options: {
306
+ body: unknown;
307
+ params: {
308
+ "*": string;
309
+ } & {};
310
+ query: unknown;
311
+ headers: unknown;
312
+ response: {
313
+ 200: Response;
314
+ 422: {
315
+ type: "validation";
316
+ on: string;
317
+ summary?: string;
318
+ message?: string;
319
+ found?: unknown;
320
+ property?: string;
321
+ expected?: string;
322
+ };
323
+ };
324
+ };
325
+ };
326
+ };
327
+ };
328
+ } & {
329
+ [x: string]: {
330
+ get: {
331
+ body: unknown;
332
+ params: {};
333
+ query: unknown;
334
+ headers: unknown;
335
+ response: {
336
+ 200: Response;
337
+ };
338
+ };
339
+ };
340
+ } & {
341
+ [x: string]: {
342
+ post: {
343
+ body: unknown;
344
+ params: {};
345
+ query: unknown;
346
+ headers: unknown;
347
+ response: {
348
+ 200: Response;
349
+ };
350
+ };
351
+ };
352
+ } & {
353
+ [x: string]: {
354
+ get: {
355
+ body: unknown;
356
+ params: {};
357
+ query: unknown;
358
+ headers: unknown;
359
+ response: {
360
+ 200: Response;
361
+ };
362
+ };
363
+ };
364
+ } & {
365
+ [x: string]: {
366
+ options: {
367
+ body: unknown;
368
+ params: {};
369
+ query: unknown;
370
+ headers: unknown;
371
+ response: {
372
+ 200: Response;
373
+ };
374
+ };
375
+ };
376
+ } & {
377
+ [x: string]: {
378
+ post: {
379
+ body: unknown;
380
+ params: {};
381
+ query: unknown;
382
+ headers: unknown;
383
+ response: {
384
+ 200: Response;
385
+ };
386
+ };
387
+ };
388
+ } & {
389
+ [x: string]: {
390
+ get: {
391
+ body: unknown;
392
+ params: {};
393
+ query: unknown;
394
+ headers: unknown;
395
+ response: {
396
+ 200: Response;
397
+ };
398
+ };
399
+ };
400
+ } & {
401
+ [x: string]: {
402
+ options: {
403
+ body: unknown;
404
+ params: {};
405
+ query: unknown;
406
+ headers: unknown;
407
+ response: {
408
+ 200: Response;
409
+ };
410
+ };
411
+ };
412
+ }, {
413
+ derive: {};
414
+ resolve: {};
415
+ schema: {};
416
+ standaloneSchema: {};
417
+ response: {};
418
+ }, {
419
+ derive: {};
420
+ resolve: {};
421
+ schema: {};
422
+ standaloneSchema: {};
423
+ response: {};
424
+ }>;
425
+ export type OAuthProviderPlugin<Props> = ReturnType<typeof oauthProvider<Props>>;
426
+ //# sourceMappingURL=plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,OAAO,EAAE,iBAAiB,EAAE,KAAK,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAU/E,OAAO,KAAK,EACV,WAAW,EACX,UAAU,EACV,4BAA4B,EAC5B,YAAY,EACZ,YAAY,EACZ,mBAAmB,EACnB,kBAAkB,EAClB,0BAA0B,EAC1B,SAAS,EACV,MAAM,YAAY,CAAC;AAEpB,wGAAwG;AACxG,MAAM,WAAW,YAAY,CAAC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AuthStorage } from './types.js';
2
+ export interface ConformanceOptions {
3
+ /**
4
+ * Called before each test; must return a fresh/empty storage (or one whose
5
+ * keys under `keyPrefix` are unused). Async allowed.
6
+ */
7
+ create: () => Promise<OAuthStorage> | OAuthStorage;
8
+ /** Called after each test to release resources. */
9
+ destroy?: (storage: OAuthStorage) => Promise<void> | void;
10
+ /**
11
+ * Prefix every key with this so the suite can run against a shared backend
12
+ * (e.g. a real Redis). Defaults to a random per-run prefix.
13
+ */
14
+ keyPrefix?: string;
15
+ /**
16
+ * How long to wait (ms) for a key with `ttlSeconds: 1` to disappear.
17
+ * Real backends may need slightly more than 1000ms. Defaults to 1500.
18
+ */
19
+ ttlWaitMs?: number;
20
+ /**
21
+ * Optional fake-clock advance. When provided the suite uses it instead of
22
+ * sleeping for TTL tests.
23
+ */
24
+ advanceTime?: (ms: number) => void;
25
+ }
26
+ /**
27
+ * Behavioural test-suite every `OAuthStorage` adapter must pass.
28
+ *
29
+ * Usage (inside a `bun test` file):
30
+ * ```ts
31
+ * import { runStorageConformance } from '@20baht/elysia-oauth-provider/storage/conformance'
32
+ * runStorageConformance('MyStorage', { create: () => new MyStorage() })
33
+ * ```
34
+ */
35
+ export declare function runStorageConformance(name: string, options: ConformanceOptions): void;
36
+ //# sourceMappingURL=conformance.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conformance.d.ts","sourceRoot":"","sources":["../../src/storage/conformance.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,MAAM,EAAE,MAAM,OAAO,CAAC,YAAY,CAAC,GAAG,YAAY,CAAC;IACnD,mDAAmD;IACnD,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC1D;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,WAAW,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;CACpC;AAID;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,kBAAkB,GAAG,IAAI,CA6LrF"}
@@ -0,0 +1,163 @@
1
+ // src/storage/conformance.ts
2
+ import { describe, expect, it } from "bun:test";
3
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
4
+ function runStorageConformance(name, options) {
5
+ const prefix = options.keyPrefix ?? `conf:${crypto.randomUUID()}:`;
6
+ const k = (s) => `${prefix}${s}`;
7
+ const ttlWait = options.ttlWaitMs ?? 1500;
8
+ const withStorage = async (fn) => {
9
+ const s = await options.create();
10
+ try {
11
+ await fn(s);
12
+ } finally {
13
+ for (const key of await s.list(prefix))
14
+ await s.delete(key);
15
+ await options.destroy?.(s);
16
+ }
17
+ };
18
+ describe(`OAuthStorage conformance: ${name}`, () => {
19
+ it("returns null for a missing key", () => withStorage(async (s) => {
20
+ expect(await s.get(k("missing"))).toBeNull();
21
+ }));
22
+ it("round-trips JSON values structurally", () => withStorage(async (s) => {
23
+ const value = { a: 1, b: "two", c: [1, 2, 3], d: { nested: true }, e: null };
24
+ await s.set(k("obj"), value);
25
+ expect(await s.get(k("obj"))).toEqual(value);
26
+ await s.set(k("str"), "plain");
27
+ expect(await s.get(k("str"))).toBe("plain");
28
+ await s.set(k("num"), 42);
29
+ expect(await s.get(k("num"))).toBe(42);
30
+ await s.set(k("arr"), ["x"]);
31
+ expect(await s.get(k("arr"))).toEqual(["x"]);
32
+ }));
33
+ it("does not leak references to stored values", () => withStorage(async (s) => {
34
+ const value = { list: [1] };
35
+ await s.set(k("ref"), value);
36
+ value.list.push(2);
37
+ const read = await s.get(k("ref"));
38
+ expect(read.list).toEqual([1]);
39
+ read.list.push(3);
40
+ expect(await s.get(k("ref"))).toEqual({ list: [1] });
41
+ }));
42
+ it("overwrites an existing key", () => withStorage(async (s) => {
43
+ await s.set(k("ow"), "one");
44
+ await s.set(k("ow"), "two");
45
+ expect(await s.get(k("ow"))).toBe("two");
46
+ }));
47
+ it("deletes a key (and tolerates deleting a missing key)", () => withStorage(async (s) => {
48
+ await s.set(k("del"), 1);
49
+ await s.delete(k("del"));
50
+ expect(await s.get(k("del"))).toBeNull();
51
+ await s.delete(k("never-existed"));
52
+ }));
53
+ it("lists keys by prefix only", () => withStorage(async (s) => {
54
+ await s.set(k("grant:u1:g1"), 1);
55
+ await s.set(k("grant:u1:g2"), 1);
56
+ await s.set(k("grant:u10:g1"), 1);
57
+ await s.set(k("token:u1:g1:abc"), 1);
58
+ const listed = (await s.list(k("grant:u1:"))).sort();
59
+ expect(listed).toEqual([k("grant:u1:g1"), k("grant:u1:g2")]);
60
+ expect(await s.list(k("nothing:"))).toEqual([]);
61
+ }));
62
+ it("expires keys after ttlSeconds", () => withStorage(async (s) => {
63
+ await s.set(k("ttl"), "soon", { ttlSeconds: 1 });
64
+ await s.set(k("keep"), "forever");
65
+ expect(await s.get(k("ttl"))).toBe("soon");
66
+ if (options.advanceTime)
67
+ options.advanceTime(1100);
68
+ else
69
+ await sleep(ttlWait);
70
+ expect(await s.get(k("ttl"))).toBeNull();
71
+ expect(await s.list(k("ttl"))).toEqual([]);
72
+ expect(await s.get(k("keep"))).toBe("forever");
73
+ }));
74
+ it("re-setting a key without ttl removes the previous ttl", () => withStorage(async (s) => {
75
+ await s.set(k("rettl"), "a", { ttlSeconds: 1 });
76
+ await s.set(k("rettl"), "b");
77
+ if (options.advanceTime)
78
+ options.advanceTime(1100);
79
+ else
80
+ await sleep(ttlWait);
81
+ expect(await s.get(k("rettl"))).toBe("b");
82
+ }));
83
+ it("re-setting a key with a new ttl replaces the old ttl", () => withStorage(async (s) => {
84
+ await s.set(k("rettl2"), "a", { ttlSeconds: 1 });
85
+ await s.set(k("rettl2"), "b", { ttlSeconds: 60 });
86
+ if (options.advanceTime)
87
+ options.advanceTime(1100);
88
+ else
89
+ await sleep(ttlWait);
90
+ expect(await s.get(k("rettl2"))).toBe("b");
91
+ }));
92
+ it("consume reads and deletes atomically", () => withStorage(async (s) => {
93
+ await s.set(k("c1"), { n: 1 });
94
+ expect(await s.consume(k("c1"))).toEqual({ n: 1 });
95
+ expect(await s.get(k("c1"))).toBeNull();
96
+ expect(await s.consume(k("c1"))).toBeNull();
97
+ expect(await s.consume(k("c-missing"))).toBeNull();
98
+ await s.set(k("c2"), "once");
99
+ const results = await Promise.all(Array.from({ length: 10 }, () => s.consume(k("c2"))));
100
+ expect(results.filter((r) => r !== null)).toEqual(["once"]);
101
+ }));
102
+ it("compareAndSet writes only when the stored version matches", () => withStorage(async (s) => {
103
+ expect(await s.compareAndSet(k("cas-missing"), 0, { version: 1 })).toBe(false);
104
+ expect(await s.get(k("cas-missing"))).toBeNull();
105
+ await s.set(k("cas"), { version: 3, body: "a" });
106
+ expect(await s.compareAndSet(k("cas"), 2, { version: 3, body: "stale" })).toBe(false);
107
+ expect(await s.get(k("cas"))).toEqual({ version: 3, body: "a" });
108
+ expect(await s.compareAndSet(k("cas"), 3, { version: 4, body: "b" })).toBe(true);
109
+ expect(await s.get(k("cas"))).toEqual({ version: 4, body: "b" });
110
+ await s.set(k("cas-nover"), { body: "no version field" });
111
+ expect(await s.compareAndSet(k("cas-nover"), 0, { version: 1 })).toBe(false);
112
+ }));
113
+ it("compareAndSet applies and replaces the ttl", () => withStorage(async (s) => {
114
+ await s.set(k("cas-ttl"), { version: 0 }, { ttlSeconds: 60 });
115
+ expect(await s.compareAndSet(k("cas-ttl"), 0, { version: 1 }, { ttlSeconds: 1 })).toBe(true);
116
+ if (options.advanceTime)
117
+ options.advanceTime(1100);
118
+ else
119
+ await sleep(ttlWait);
120
+ expect(await s.get(k("cas-ttl"))).toBeNull();
121
+ expect(await s.compareAndSet(k("cas-ttl"), 1, { version: 2 })).toBe(false);
122
+ }));
123
+ it("of concurrent compareAndSet calls at one version exactly one wins", () => withStorage(async (s) => {
124
+ await s.set(k("cas-race"), { version: 0 });
125
+ const results = await Promise.all(Array.from({ length: 10 }, (_, i) => s.compareAndSet(k("cas-race"), 0, { version: 1, writer: i })));
126
+ expect(results.filter(Boolean)).toHaveLength(1);
127
+ const winner = results.indexOf(true);
128
+ expect(await s.get(k("cas-race"))).toEqual({ version: 1, writer: winner });
129
+ }));
130
+ it("compareAndDelete removes only a matching version", () => withStorage(async (s) => {
131
+ expect(await s.compareAndDelete(k("cad-missing"), 0)).toBe(false);
132
+ await s.set(k("cad"), { version: 5 });
133
+ expect(await s.compareAndDelete(k("cad"), 4)).toBe(false);
134
+ expect(await s.get(k("cad"))).toEqual({ version: 5 });
135
+ expect(await s.compareAndDelete(k("cad"), 5)).toBe(true);
136
+ expect(await s.get(k("cad"))).toBeNull();
137
+ expect(await s.compareAndDelete(k("cad"), 5)).toBe(false);
138
+ await s.set(k("cad-race"), { version: 1 });
139
+ const results = await Promise.all(Array.from({ length: 10 }, () => s.compareAndDelete(k("cad-race"), 1)));
140
+ expect(results.filter(Boolean)).toHaveLength(1);
141
+ }));
142
+ it("compareAndSet and compareAndDelete cannot both win on one version", () => withStorage(async (s) => {
143
+ await s.set(k("mix"), { version: 7 });
144
+ const [set, del] = await Promise.all([
145
+ s.compareAndSet(k("mix"), 7, { version: 8 }),
146
+ s.compareAndDelete(k("mix"), 7)
147
+ ]);
148
+ expect([set, del].filter(Boolean)).toHaveLength(1);
149
+ expect(await s.get(k("mix"))).toEqual(set ? { version: 8 } : null);
150
+ }));
151
+ it("handles many keys and concurrent writes", () => withStorage(async (s) => {
152
+ await Promise.all(Array.from({ length: 200 }, (_, i) => s.set(k(`bulk:${i}`), i)));
153
+ expect((await s.list(k("bulk:"))).length).toBe(200);
154
+ expect(await s.get(k("bulk:199"))).toBe(199);
155
+ }));
156
+ });
157
+ }
158
+ export {
159
+ runStorageConformance
160
+ };
161
+
162
+ //# debugId=3BF424E0FFE2160764756E2164756E21
163
+ //# sourceMappingURL=conformance.js.map