@adonisjs/auth 9.0.0-9 → 9.0.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 (125) hide show
  1. package/build/chunk-3HZHOWKL.js +8 -0
  2. package/build/chunk-3HZHOWKL.js.map +1 -0
  3. package/build/chunk-52DVKHJR.js +246 -0
  4. package/build/chunk-52DVKHJR.js.map +1 -0
  5. package/build/chunk-BHB55PBJ.js +197 -0
  6. package/build/chunk-BHB55PBJ.js.map +1 -0
  7. package/build/chunk-CZCFTIBB.js +21 -0
  8. package/build/chunk-CZCFTIBB.js.map +1 -0
  9. package/build/index.d.ts +7 -6
  10. package/build/index.js +146 -15
  11. package/build/index.js.map +1 -0
  12. package/build/modules/access_tokens_guard/access_token.d.ts +137 -0
  13. package/build/modules/access_tokens_guard/crc32.d.ts +16 -0
  14. package/build/modules/access_tokens_guard/define_config.d.ts +17 -0
  15. package/build/modules/access_tokens_guard/guard.d.ts +81 -0
  16. package/build/modules/access_tokens_guard/main.d.ts +5 -0
  17. package/build/modules/access_tokens_guard/main.js +929 -0
  18. package/build/modules/access_tokens_guard/main.js.map +1 -0
  19. package/build/modules/access_tokens_guard/token_providers/db.d.ts +76 -0
  20. package/build/modules/access_tokens_guard/types.d.ts +208 -0
  21. package/build/modules/access_tokens_guard/types.js +1 -0
  22. package/build/modules/access_tokens_guard/types.js.map +1 -0
  23. package/build/modules/access_tokens_guard/user_providers/lucid.d.ts +53 -0
  24. package/build/modules/session_guard/define_config.d.ts +17 -0
  25. package/build/modules/session_guard/guard.d.ts +98 -0
  26. package/build/modules/session_guard/main.d.ts +5 -0
  27. package/build/modules/session_guard/main.js +741 -0
  28. package/build/modules/session_guard/main.js.map +1 -0
  29. package/build/modules/session_guard/remember_me_token.d.ts +88 -0
  30. package/build/modules/session_guard/token_providers/db.d.ts +69 -0
  31. package/build/modules/session_guard/types.d.ts +243 -0
  32. package/build/modules/session_guard/types.js +1 -0
  33. package/build/modules/session_guard/types.js.map +1 -0
  34. package/build/modules/session_guard/user_providers/lucid.d.ts +57 -0
  35. package/build/providers/auth_provider.d.ts +1 -1
  36. package/build/providers/auth_provider.js +31 -27
  37. package/build/providers/auth_provider.js.map +1 -0
  38. package/build/services/auth.d.ts +1 -1
  39. package/build/services/auth.js +10 -15
  40. package/build/services/auth.js.map +1 -0
  41. package/build/src/{auth/auth_manager.d.ts → auth_manager.d.ts} +8 -3
  42. package/build/src/authenticator.d.ts +81 -0
  43. package/build/src/{auth/authenticator_client.d.ts → authenticator_client.d.ts} +4 -4
  44. package/build/src/{auth/define_config.d.ts → define_config.d.ts} +0 -10
  45. package/build/src/errors.d.ts +105 -0
  46. package/build/src/{auth/middleware → middleware}/initialize_auth_middleware.d.ts +3 -2
  47. package/build/src/middleware/initialize_auth_middleware.js +17 -0
  48. package/build/src/middleware/initialize_auth_middleware.js.map +1 -0
  49. package/build/src/mixins/with_auth_finder.d.ts +156 -0
  50. package/build/src/{auth/plugins → plugins}/japa/api_client.d.ts +8 -8
  51. package/build/src/plugins/japa/api_client.js +59 -0
  52. package/build/src/plugins/japa/api_client.js.map +1 -0
  53. package/build/src/{auth/plugins → plugins}/japa/browser_client.d.ts +10 -7
  54. package/build/src/plugins/japa/browser_client.js +67 -0
  55. package/build/src/plugins/japa/browser_client.js.map +1 -0
  56. package/build/src/{auth/types.d.ts → types.d.ts} +31 -26
  57. package/build/src/types.js +1 -0
  58. package/build/src/types.js.map +1 -0
  59. package/package.json +88 -68
  60. package/build/configure.js +0 -47
  61. package/build/factories/basic_auth_guard_factory.d.ts +0 -12
  62. package/build/factories/basic_auth_guard_factory.js +0 -22
  63. package/build/factories/database_token_factory.d.ts +0 -36
  64. package/build/factories/database_token_factory.js +0 -54
  65. package/build/factories/database_user_provider.d.ts +0 -14
  66. package/build/factories/database_user_provider.js +0 -27
  67. package/build/factories/lucid_user_provider.d.ts +0 -28
  68. package/build/factories/lucid_user_provider.js +0 -68
  69. package/build/factories/main.d.ts +0 -4
  70. package/build/factories/main.js +0 -12
  71. package/build/factories/session_guard_factory.d.ts +0 -13
  72. package/build/factories/session_guard_factory.js +0 -24
  73. package/build/src/auth/auth_manager.js +0 -41
  74. package/build/src/auth/authenticator.d.ts +0 -63
  75. package/build/src/auth/authenticator.js +0 -129
  76. package/build/src/auth/authenticator_client.js +0 -59
  77. package/build/src/auth/debug.js +0 -10
  78. package/build/src/auth/define_config.js +0 -54
  79. package/build/src/auth/errors.d.ts +0 -90
  80. package/build/src/auth/errors.js +0 -201
  81. package/build/src/auth/middleware/initialize_auth_middleware.js +0 -25
  82. package/build/src/auth/plugins/japa/api_client.js +0 -63
  83. package/build/src/auth/plugins/japa/browser_client.js +0 -64
  84. package/build/src/auth/symbols.js +0 -17
  85. package/build/src/auth/types.js +0 -9
  86. package/build/src/auth/user_providers/main.d.ts +0 -15
  87. package/build/src/auth/user_providers/main.js +0 -22
  88. package/build/src/core/guard_user.d.ts +0 -26
  89. package/build/src/core/guard_user.js +0 -29
  90. package/build/src/core/token.d.ts +0 -89
  91. package/build/src/core/token.js +0 -114
  92. package/build/src/core/token_providers/database.d.ts +0 -77
  93. package/build/src/core/token_providers/database.js +0 -113
  94. package/build/src/core/types.d.ts +0 -178
  95. package/build/src/core/types.js +0 -9
  96. package/build/src/core/user_providers/database.d.ts +0 -78
  97. package/build/src/core/user_providers/database.js +0 -117
  98. package/build/src/core/user_providers/lucid.d.ts +0 -61
  99. package/build/src/core/user_providers/lucid.js +0 -122
  100. package/build/src/guards/basic_auth/define_config.d.ts +0 -16
  101. package/build/src/guards/basic_auth/define_config.js +0 -38
  102. package/build/src/guards/basic_auth/guard.d.ts +0 -70
  103. package/build/src/guards/basic_auth/guard.js +0 -190
  104. package/build/src/guards/basic_auth/main.d.ts +0 -2
  105. package/build/src/guards/basic_auth/main.js +0 -10
  106. package/build/src/guards/basic_auth/types.d.ts +0 -35
  107. package/build/src/guards/basic_auth/types.js +0 -9
  108. package/build/src/guards/session/define_config.d.ts +0 -23
  109. package/build/src/guards/session/define_config.js +0 -56
  110. package/build/src/guards/session/guard.d.ts +0 -123
  111. package/build/src/guards/session/guard.js +0 -510
  112. package/build/src/guards/session/main.d.ts +0 -3
  113. package/build/src/guards/session/main.js +0 -11
  114. package/build/src/guards/session/token.d.ts +0 -57
  115. package/build/src/guards/session/token.js +0 -58
  116. package/build/src/guards/session/token_providers/main.d.ts +0 -33
  117. package/build/src/guards/session/token_providers/main.js +0 -42
  118. package/build/src/guards/session/types.d.ts +0 -104
  119. package/build/src/guards/session/types.js +0 -9
  120. package/build/stubs/main.d.ts +0 -1
  121. package/build/stubs/main.js +0 -10
  122. package/build/stubs/middleware/auth_middleware.stub +0 -30
  123. package/build/stubs/middleware/guest_middleware.stub +0 -36
  124. /package/build/src/{auth/debug.d.ts → debug.d.ts} +0 -0
  125. /package/build/src/{auth/symbols.d.ts → symbols.d.ts} +0 -0
@@ -0,0 +1,929 @@
1
+ import {
2
+ E_UNAUTHORIZED_ACCESS
3
+ } from "../../chunk-BHB55PBJ.js";
4
+ import "../../chunk-CZCFTIBB.js";
5
+
6
+ // modules/access_tokens_guard/access_token.ts
7
+ import { createHash } from "node:crypto";
8
+ import string from "@adonisjs/core/helpers/string";
9
+ import { RuntimeException } from "@adonisjs/core/exceptions";
10
+ import { Secret, base64, safeEqual } from "@adonisjs/core/helpers";
11
+
12
+ // modules/access_tokens_guard/crc32.ts
13
+ var CRC32 = class {
14
+ /**
15
+ * Lookup table calculated for 0xEDB88320 divisor
16
+ */
17
+ #lookupTable = [
18
+ 0,
19
+ 1996959894,
20
+ 3993919788,
21
+ 2567524794,
22
+ 124634137,
23
+ 1886057615,
24
+ 3915621685,
25
+ 2657392035,
26
+ 249268274,
27
+ 2044508324,
28
+ 3772115230,
29
+ 2547177864,
30
+ 162941995,
31
+ 2125561021,
32
+ 3887607047,
33
+ 2428444049,
34
+ 498536548,
35
+ 1789927666,
36
+ 4089016648,
37
+ 2227061214,
38
+ 450548861,
39
+ 1843258603,
40
+ 4107580753,
41
+ 2211677639,
42
+ 325883990,
43
+ 1684777152,
44
+ 4251122042,
45
+ 2321926636,
46
+ 335633487,
47
+ 1661365465,
48
+ 4195302755,
49
+ 2366115317,
50
+ 997073096,
51
+ 1281953886,
52
+ 3579855332,
53
+ 2724688242,
54
+ 1006888145,
55
+ 1258607687,
56
+ 3524101629,
57
+ 2768942443,
58
+ 901097722,
59
+ 1119000684,
60
+ 3686517206,
61
+ 2898065728,
62
+ 853044451,
63
+ 1172266101,
64
+ 3705015759,
65
+ 2882616665,
66
+ 651767980,
67
+ 1373503546,
68
+ 3369554304,
69
+ 3218104598,
70
+ 565507253,
71
+ 1454621731,
72
+ 3485111705,
73
+ 3099436303,
74
+ 671266974,
75
+ 1594198024,
76
+ 3322730930,
77
+ 2970347812,
78
+ 795835527,
79
+ 1483230225,
80
+ 3244367275,
81
+ 3060149565,
82
+ 1994146192,
83
+ 31158534,
84
+ 2563907772,
85
+ 4023717930,
86
+ 1907459465,
87
+ 112637215,
88
+ 2680153253,
89
+ 3904427059,
90
+ 2013776290,
91
+ 251722036,
92
+ 2517215374,
93
+ 3775830040,
94
+ 2137656763,
95
+ 141376813,
96
+ 2439277719,
97
+ 3865271297,
98
+ 1802195444,
99
+ 476864866,
100
+ 2238001368,
101
+ 4066508878,
102
+ 1812370925,
103
+ 453092731,
104
+ 2181625025,
105
+ 4111451223,
106
+ 1706088902,
107
+ 314042704,
108
+ 2344532202,
109
+ 4240017532,
110
+ 1658658271,
111
+ 366619977,
112
+ 2362670323,
113
+ 4224994405,
114
+ 1303535960,
115
+ 984961486,
116
+ 2747007092,
117
+ 3569037538,
118
+ 1256170817,
119
+ 1037604311,
120
+ 2765210733,
121
+ 3554079995,
122
+ 1131014506,
123
+ 879679996,
124
+ 2909243462,
125
+ 3663771856,
126
+ 1141124467,
127
+ 855842277,
128
+ 2852801631,
129
+ 3708648649,
130
+ 1342533948,
131
+ 654459306,
132
+ 3188396048,
133
+ 3373015174,
134
+ 1466479909,
135
+ 544179635,
136
+ 3110523913,
137
+ 3462522015,
138
+ 1591671054,
139
+ 702138776,
140
+ 2966460450,
141
+ 3352799412,
142
+ 1504918807,
143
+ 783551873,
144
+ 3082640443,
145
+ 3233442989,
146
+ 3988292384,
147
+ 2596254646,
148
+ 62317068,
149
+ 1957810842,
150
+ 3939845945,
151
+ 2647816111,
152
+ 81470997,
153
+ 1943803523,
154
+ 3814918930,
155
+ 2489596804,
156
+ 225274430,
157
+ 2053790376,
158
+ 3826175755,
159
+ 2466906013,
160
+ 167816743,
161
+ 2097651377,
162
+ 4027552580,
163
+ 2265490386,
164
+ 503444072,
165
+ 1762050814,
166
+ 4150417245,
167
+ 2154129355,
168
+ 426522225,
169
+ 1852507879,
170
+ 4275313526,
171
+ 2312317920,
172
+ 282753626,
173
+ 1742555852,
174
+ 4189708143,
175
+ 2394877945,
176
+ 397917763,
177
+ 1622183637,
178
+ 3604390888,
179
+ 2714866558,
180
+ 953729732,
181
+ 1340076626,
182
+ 3518719985,
183
+ 2797360999,
184
+ 1068828381,
185
+ 1219638859,
186
+ 3624741850,
187
+ 2936675148,
188
+ 906185462,
189
+ 1090812512,
190
+ 3747672003,
191
+ 2825379669,
192
+ 829329135,
193
+ 1181335161,
194
+ 3412177804,
195
+ 3160834842,
196
+ 628085408,
197
+ 1382605366,
198
+ 3423369109,
199
+ 3138078467,
200
+ 570562233,
201
+ 1426400815,
202
+ 3317316542,
203
+ 2998733608,
204
+ 733239954,
205
+ 1555261956,
206
+ 3268935591,
207
+ 3050360625,
208
+ 752459403,
209
+ 1541320221,
210
+ 2607071920,
211
+ 3965973030,
212
+ 1969922972,
213
+ 40735498,
214
+ 2617837225,
215
+ 3943577151,
216
+ 1913087877,
217
+ 83908371,
218
+ 2512341634,
219
+ 3803740692,
220
+ 2075208622,
221
+ 213261112,
222
+ 2463272603,
223
+ 3855990285,
224
+ 2094854071,
225
+ 198958881,
226
+ 2262029012,
227
+ 4057260610,
228
+ 1759359992,
229
+ 534414190,
230
+ 2176718541,
231
+ 4139329115,
232
+ 1873836001,
233
+ 414664567,
234
+ 2282248934,
235
+ 4279200368,
236
+ 1711684554,
237
+ 285281116,
238
+ 2405801727,
239
+ 4167216745,
240
+ 1634467795,
241
+ 376229701,
242
+ 2685067896,
243
+ 3608007406,
244
+ 1308918612,
245
+ 956543938,
246
+ 2808555105,
247
+ 3495958263,
248
+ 1231636301,
249
+ 1047427035,
250
+ 2932959818,
251
+ 3654703836,
252
+ 1088359270,
253
+ 936918e3,
254
+ 2847714899,
255
+ 3736837829,
256
+ 1202900863,
257
+ 817233897,
258
+ 3183342108,
259
+ 3401237130,
260
+ 1404277552,
261
+ 615818150,
262
+ 3134207493,
263
+ 3453421203,
264
+ 1423857449,
265
+ 601450431,
266
+ 3009837614,
267
+ 3294710456,
268
+ 1567103746,
269
+ 711928724,
270
+ 3020668471,
271
+ 3272380065,
272
+ 1510334235,
273
+ 755167117
274
+ ];
275
+ #initialCRC = 4294967295;
276
+ #calculateBytes(bytes, accumulator) {
277
+ let crc = accumulator || this.#initialCRC;
278
+ for (const byte of bytes) {
279
+ const tableIndex = (crc ^ byte) & 255;
280
+ const tableVal = this.#lookupTable[tableIndex];
281
+ crc = crc >>> 8 ^ tableVal;
282
+ }
283
+ return crc;
284
+ }
285
+ #crcToUint(crc) {
286
+ return this.#toUint32(crc ^ 4294967295);
287
+ }
288
+ #strToBytes(input) {
289
+ const encoder = new TextEncoder();
290
+ return encoder.encode(input);
291
+ }
292
+ #toUint32(num) {
293
+ if (num >= 0) {
294
+ return num;
295
+ }
296
+ return 4294967295 - num * -1 + 1;
297
+ }
298
+ calculate(input) {
299
+ return this.forString(input);
300
+ }
301
+ forString(input) {
302
+ const bytes = this.#strToBytes(input);
303
+ return this.forBytes(bytes);
304
+ }
305
+ forBytes(bytes, accumulator) {
306
+ const crc = this.#calculateBytes(bytes, accumulator);
307
+ return this.#crcToUint(crc);
308
+ }
309
+ };
310
+
311
+ // modules/access_tokens_guard/access_token.ts
312
+ var AccessToken = class {
313
+ /**
314
+ * Decodes a publicly shared token and return the series
315
+ * and the token value from it.
316
+ *
317
+ * Returns null when unable to decode the token because of
318
+ * invalid format or encoding.
319
+ */
320
+ static decode(prefix, value) {
321
+ if (typeof value !== "string" || !value.startsWith(`${prefix}`)) {
322
+ return null;
323
+ }
324
+ const token = value.replace(new RegExp(`^${prefix}`), "");
325
+ if (!token) {
326
+ return null;
327
+ }
328
+ const [identifier, ...tokenValue] = token.split(".");
329
+ if (!identifier || tokenValue.length === 0) {
330
+ return null;
331
+ }
332
+ const decodedIdentifier = base64.urlDecode(identifier);
333
+ const decodedSecret = base64.urlDecode(tokenValue.join("."));
334
+ if (!decodedIdentifier || !decodedSecret) {
335
+ return null;
336
+ }
337
+ return {
338
+ identifier: decodedIdentifier,
339
+ secret: new Secret(decodedSecret)
340
+ };
341
+ }
342
+ /**
343
+ * Creates a transient token that can be shared with the persistence
344
+ * layer.
345
+ */
346
+ static createTransientToken(userId, size, expiresIn) {
347
+ let expiresAt;
348
+ if (expiresIn) {
349
+ expiresAt = /* @__PURE__ */ new Date();
350
+ expiresAt.setSeconds(expiresAt.getSeconds() + string.seconds.parse(expiresIn));
351
+ }
352
+ return {
353
+ userId,
354
+ expiresAt,
355
+ ...this.seed(size)
356
+ };
357
+ }
358
+ /**
359
+ * Creates a secret opaque token and its hash. The secret is
360
+ * suffixed with a crc32 checksum for secret scanning tools
361
+ * to easily identify the token.
362
+ */
363
+ static seed(size) {
364
+ const seed = string.random(size);
365
+ const secret = new Secret(`${seed}${new CRC32().calculate(seed)}`);
366
+ const hash = createHash("sha256").update(secret.release()).digest("hex");
367
+ return { secret, hash };
368
+ }
369
+ /**
370
+ * Identifer is a unique sequence to identify the
371
+ * token within database. It should be the
372
+ * primary/unique key
373
+ */
374
+ identifier;
375
+ /**
376
+ * Reference to the user id for whom the token
377
+ * is generated.
378
+ */
379
+ tokenableId;
380
+ /**
381
+ * The value is a public representation of a token. It is created
382
+ * by combining the "identifier"."secret"
383
+ */
384
+ value;
385
+ /**
386
+ * Recognizable name for the token
387
+ */
388
+ name;
389
+ /**
390
+ * A unique type to identify a bucket of tokens inside the
391
+ * storage layer.
392
+ */
393
+ type;
394
+ /**
395
+ * Hash is computed from the seed to later verify the validity
396
+ * of seed
397
+ */
398
+ hash;
399
+ /**
400
+ * Date/time when the token instance was created
401
+ */
402
+ createdAt;
403
+ /**
404
+ * Date/time when the token was updated
405
+ */
406
+ updatedAt;
407
+ /**
408
+ * Timestamp at which the token was used for authentication
409
+ */
410
+ lastUsedAt;
411
+ /**
412
+ * Timestamp at which the token will expire
413
+ */
414
+ expiresAt;
415
+ /**
416
+ * An array of abilities the token can perform. The abilities
417
+ * is an array of abritary string values
418
+ */
419
+ abilities;
420
+ constructor(attributes) {
421
+ this.identifier = attributes.identifier;
422
+ this.tokenableId = attributes.tokenableId;
423
+ this.name = attributes.name;
424
+ this.hash = attributes.hash;
425
+ this.type = attributes.type;
426
+ this.createdAt = attributes.createdAt;
427
+ this.updatedAt = attributes.updatedAt;
428
+ this.expiresAt = attributes.expiresAt;
429
+ this.lastUsedAt = attributes.lastUsedAt;
430
+ this.abilities = attributes.abilities || ["*"];
431
+ if (attributes.secret) {
432
+ if (!attributes.prefix) {
433
+ throw new RuntimeException("Cannot compute token value without the prefix");
434
+ }
435
+ this.value = new Secret(
436
+ `${attributes.prefix}${base64.urlEncode(String(this.identifier))}.${base64.urlEncode(
437
+ attributes.secret.release()
438
+ )}`
439
+ );
440
+ }
441
+ }
442
+ /**
443
+ * Check if the token allows the given ability.
444
+ */
445
+ allows(ability) {
446
+ return this.abilities.includes(ability) || this.abilities.includes("*");
447
+ }
448
+ /**
449
+ * Check if the token denies the ability.
450
+ */
451
+ denies(ability) {
452
+ return !this.abilities.includes(ability) && !this.abilities.includes("*");
453
+ }
454
+ /**
455
+ * Authorize ability access using the current access token
456
+ */
457
+ authorize(ability) {
458
+ if (this.denies(ability)) {
459
+ throw new E_UNAUTHORIZED_ACCESS("Unauthorized access", { guardDriverName: "access_tokens" });
460
+ }
461
+ }
462
+ /**
463
+ * Check if the token has been expired. Verifies
464
+ * the "expiresAt" timestamp with the current
465
+ * date.
466
+ *
467
+ * Tokens with no expiry never expire
468
+ */
469
+ isExpired() {
470
+ if (!this.expiresAt) {
471
+ return false;
472
+ }
473
+ return this.expiresAt < /* @__PURE__ */ new Date();
474
+ }
475
+ /**
476
+ * Verifies the value of a token against the pre-defined hash
477
+ */
478
+ verify(secret) {
479
+ const newHash = createHash("sha256").update(secret.release()).digest("hex");
480
+ return safeEqual(this.hash, newHash);
481
+ }
482
+ toJSON() {
483
+ return {
484
+ type: "bearer",
485
+ name: this.name,
486
+ token: this.value ? this.value.release() : void 0,
487
+ abilities: this.abilities,
488
+ lastUsedAt: this.lastUsedAt,
489
+ expiresAt: this.expiresAt
490
+ };
491
+ }
492
+ };
493
+
494
+ // modules/access_tokens_guard/guard.ts
495
+ import { Secret as Secret2 } from "@adonisjs/core/helpers";
496
+ var AccessTokensGuard = class {
497
+ /**
498
+ * A unique name for the guard.
499
+ */
500
+ #name;
501
+ /**
502
+ * Reference to the current HTTP context
503
+ */
504
+ #ctx;
505
+ /**
506
+ * Provider to lookup user details
507
+ */
508
+ #userProvider;
509
+ /**
510
+ * Emitter to emit events
511
+ */
512
+ #emitter;
513
+ /**
514
+ * Driver name of the guard
515
+ */
516
+ driverName = "access_tokens";
517
+ /**
518
+ * Whether or not the authentication has been attempted
519
+ * during the current request.
520
+ */
521
+ authenticationAttempted = false;
522
+ /**
523
+ * A boolean to know if the current request has
524
+ * been authenticated
525
+ */
526
+ isAuthenticated = false;
527
+ /**
528
+ * Reference to an instance of the authenticated user.
529
+ * The value only exists after calling one of the
530
+ * following methods.
531
+ *
532
+ * - authenticate
533
+ * - check
534
+ *
535
+ * You can use the "getUserOrFail" method to throw an exception if
536
+ * the request is not authenticated.
537
+ */
538
+ user;
539
+ constructor(name, ctx, emitter, userProvider) {
540
+ this.#name = name;
541
+ this.#ctx = ctx;
542
+ this.#emitter = emitter;
543
+ this.#userProvider = userProvider;
544
+ }
545
+ /**
546
+ * Emits authentication failure and returns an exception
547
+ * to end the authentication cycle.
548
+ */
549
+ #authenticationFailed() {
550
+ const error = new E_UNAUTHORIZED_ACCESS("Unauthorized access", {
551
+ guardDriverName: this.driverName
552
+ });
553
+ this.#emitter.emit("access_tokens_auth:authentication_failed", {
554
+ ctx: this.#ctx,
555
+ guardName: this.#name,
556
+ error
557
+ });
558
+ return error;
559
+ }
560
+ /**
561
+ * Returns the bearer token from the request headers or fails
562
+ */
563
+ #getBearerToken() {
564
+ const bearerToken = this.#ctx.request.header("authorization", "");
565
+ const [, token] = bearerToken.split("Bearer ");
566
+ if (!token) {
567
+ throw this.#authenticationFailed();
568
+ }
569
+ return token;
570
+ }
571
+ /**
572
+ * Returns an instance of the authenticated user. Or throws
573
+ * an exception if the request is not authenticated.
574
+ */
575
+ getUserOrFail() {
576
+ if (!this.user) {
577
+ throw new E_UNAUTHORIZED_ACCESS("Unauthorized access", {
578
+ guardDriverName: this.driverName
579
+ });
580
+ }
581
+ return this.user;
582
+ }
583
+ /**
584
+ * Authenticate the current HTTP request by verifying the bearer
585
+ * token or fails with an exception
586
+ */
587
+ async authenticate() {
588
+ if (this.authenticationAttempted) {
589
+ return this.getUserOrFail();
590
+ }
591
+ this.authenticationAttempted = true;
592
+ this.#emitter.emit("access_tokens_auth:authentication_attempted", {
593
+ ctx: this.#ctx,
594
+ guardName: this.#name
595
+ });
596
+ const bearerToken = new Secret2(this.#getBearerToken());
597
+ const token = await this.#userProvider.verifyToken(bearerToken);
598
+ if (!token) {
599
+ throw this.#authenticationFailed();
600
+ }
601
+ const providerUser = await this.#userProvider.findById(token.tokenableId);
602
+ if (!providerUser) {
603
+ throw this.#authenticationFailed();
604
+ }
605
+ this.isAuthenticated = true;
606
+ this.user = providerUser.getOriginal();
607
+ this.user.currentAccessToken = token;
608
+ this.#emitter.emit("access_tokens_auth:authentication_succeeded", {
609
+ ctx: this.#ctx,
610
+ token,
611
+ guardName: this.#name,
612
+ user: this.user
613
+ });
614
+ return this.user;
615
+ }
616
+ /**
617
+ * Returns the Authorization header clients can use to authenticate
618
+ * the request.
619
+ */
620
+ async authenticateAsClient(user, abilities, options) {
621
+ const token = await this.#userProvider.createToken(user, abilities, options);
622
+ return {
623
+ headers: {
624
+ authorization: `Bearer ${token.value.release()}`
625
+ }
626
+ };
627
+ }
628
+ /**
629
+ * Silently check if the user is authenticated or not. The
630
+ * method is same the "authenticate" method but does not
631
+ * throw any exceptions.
632
+ */
633
+ async check() {
634
+ try {
635
+ await this.authenticate();
636
+ return true;
637
+ } catch (error) {
638
+ if (error instanceof E_UNAUTHORIZED_ACCESS) {
639
+ return false;
640
+ }
641
+ throw error;
642
+ }
643
+ }
644
+ };
645
+
646
+ // modules/access_tokens_guard/token_providers/db.ts
647
+ import { RuntimeException as RuntimeException2 } from "@adonisjs/core/exceptions";
648
+ var DbAccessTokensProvider = class _DbAccessTokensProvider {
649
+ constructor(options) {
650
+ this.options = options;
651
+ this.table = options.table || "auth_access_tokens";
652
+ this.tokenSecretLength = options.tokenSecretLength || 40;
653
+ this.type = options.type || "auth_token";
654
+ this.prefix = options.prefix || "oat_";
655
+ }
656
+ /**
657
+ * Create tokens provider instance for a given Lucid model
658
+ */
659
+ static forModel(model, options) {
660
+ return new _DbAccessTokensProvider({ tokenableModel: model, ...options || {} });
661
+ }
662
+ /**
663
+ * A unique type for the value. The type is used to identify a
664
+ * bucket of tokens within the storage layer.
665
+ *
666
+ * Defaults to auth_token
667
+ */
668
+ type;
669
+ /**
670
+ * A unique prefix to append to the publicly shared token value.
671
+ *
672
+ * Defaults to oat
673
+ */
674
+ prefix;
675
+ /**
676
+ * Database table to use for querying access tokens
677
+ */
678
+ table;
679
+ /**
680
+ * The length for the token secret. A secret is a cryptographically
681
+ * secure random string.
682
+ */
683
+ tokenSecretLength;
684
+ /**
685
+ * Ensure the provided user is an instance of the user model and
686
+ * has a primary key
687
+ */
688
+ #ensureIsPersisted(user) {
689
+ const model = this.options.tokenableModel;
690
+ if (user instanceof model === false) {
691
+ throw new RuntimeException2(
692
+ `Invalid user object. It must be an instance of the "${model.name}" model`
693
+ );
694
+ }
695
+ if (!user.$primaryKeyValue) {
696
+ throw new RuntimeException2(
697
+ `Cannot use "${model.name}" model for managing access tokens. The value of column "${model.primaryKey}" is undefined or null`
698
+ );
699
+ }
700
+ }
701
+ /**
702
+ * Maps a database row to an instance token instance
703
+ */
704
+ dbRowToAccessToken(dbRow) {
705
+ return new AccessToken({
706
+ identifier: dbRow.id,
707
+ tokenableId: dbRow.tokenable_id,
708
+ type: dbRow.type,
709
+ name: dbRow.name,
710
+ hash: dbRow.hash,
711
+ abilities: JSON.parse(dbRow.abilities),
712
+ createdAt: typeof dbRow.created_at === "number" ? new Date(dbRow.created_at) : dbRow.created_at,
713
+ updatedAt: typeof dbRow.updated_at === "number" ? new Date(dbRow.updated_at) : dbRow.updated_at,
714
+ lastUsedAt: typeof dbRow.last_used_at === "number" ? new Date(dbRow.last_used_at) : dbRow.last_used_at,
715
+ expiresAt: typeof dbRow.expires_at === "number" ? new Date(dbRow.expires_at) : dbRow.expires_at
716
+ });
717
+ }
718
+ /**
719
+ * Returns a query client instance from the parent model
720
+ */
721
+ async getDb() {
722
+ const model = this.options.tokenableModel;
723
+ return model.$adapter.query(model).client;
724
+ }
725
+ /**
726
+ * Create a token for a user
727
+ */
728
+ async create(user, abilities = ["*"], options) {
729
+ this.#ensureIsPersisted(user);
730
+ const queryClient = await this.getDb();
731
+ const transientToken = AccessToken.createTransientToken(
732
+ user.$primaryKeyValue,
733
+ this.tokenSecretLength,
734
+ options?.expiresIn || this.options.expiresIn
735
+ );
736
+ const dbRow = {
737
+ tokenable_id: transientToken.userId,
738
+ type: this.type,
739
+ name: options?.name || null,
740
+ hash: transientToken.hash,
741
+ abilities: JSON.stringify(abilities),
742
+ created_at: /* @__PURE__ */ new Date(),
743
+ updated_at: /* @__PURE__ */ new Date(),
744
+ last_used_at: null,
745
+ expires_at: transientToken.expiresAt || null
746
+ };
747
+ const [id] = await queryClient.table(this.table).insert(dbRow);
748
+ return new AccessToken({
749
+ identifier: id,
750
+ tokenableId: dbRow.tokenable_id,
751
+ type: dbRow.type,
752
+ prefix: this.prefix,
753
+ secret: transientToken.secret,
754
+ name: dbRow.name,
755
+ hash: dbRow.hash,
756
+ abilities: JSON.parse(dbRow.abilities),
757
+ createdAt: dbRow.created_at,
758
+ updatedAt: dbRow.updated_at,
759
+ lastUsedAt: dbRow.last_used_at,
760
+ expiresAt: dbRow.expires_at
761
+ });
762
+ }
763
+ /**
764
+ * Find a token for a user by the token id
765
+ */
766
+ async find(user, identifier) {
767
+ this.#ensureIsPersisted(user);
768
+ const queryClient = await this.getDb();
769
+ const dbRow = await queryClient.query().from(this.table).where({ id: identifier, tokenable_id: user.$primaryKeyValue, type: this.type }).limit(1).first();
770
+ if (!dbRow) {
771
+ return null;
772
+ }
773
+ return this.dbRowToAccessToken(dbRow);
774
+ }
775
+ /**
776
+ * Delete a token by its id
777
+ */
778
+ async delete(user, identifier) {
779
+ this.#ensureIsPersisted(user);
780
+ const queryClient = await this.getDb();
781
+ const affectedRows = await queryClient.query().from(this.table).where({ id: identifier, tokenable_id: user.$primaryKeyValue, type: this.type }).del().exec();
782
+ return affectedRows;
783
+ }
784
+ /**
785
+ * Returns all the tokens a given user
786
+ */
787
+ async all(user) {
788
+ this.#ensureIsPersisted(user);
789
+ const queryClient = await this.getDb();
790
+ const dbRows = await queryClient.query().from(this.table).where({ tokenable_id: user.$primaryKeyValue, type: this.type }).orderBy("last_used_at", "desc").orderBy("id", "desc").exec();
791
+ return dbRows.map((dbRow) => {
792
+ return this.dbRowToAccessToken(dbRow);
793
+ });
794
+ }
795
+ /**
796
+ * Verifies a publicly shared access token and returns an
797
+ * access token for it.
798
+ *
799
+ * Returns null when unable to verify the token or find it
800
+ * inside the storage
801
+ */
802
+ async verify(tokenValue) {
803
+ const decodedToken = AccessToken.decode(this.prefix, tokenValue.release());
804
+ if (!decodedToken) {
805
+ return null;
806
+ }
807
+ const db = await this.getDb();
808
+ const dbRow = await db.query().from(this.table).where({ id: decodedToken.identifier, type: this.type }).limit(1).first();
809
+ if (!dbRow) {
810
+ return null;
811
+ }
812
+ dbRow.last_used_at = /* @__PURE__ */ new Date();
813
+ await db.from(this.table).where({ id: dbRow.id, type: dbRow.type }).update({ last_used_at: dbRow.last_used_at });
814
+ const accessToken = this.dbRowToAccessToken(dbRow);
815
+ if (!accessToken.verify(decodedToken.secret) || accessToken.isExpired()) {
816
+ return null;
817
+ }
818
+ return accessToken;
819
+ }
820
+ };
821
+
822
+ // modules/access_tokens_guard/user_providers/lucid.ts
823
+ import { RuntimeException as RuntimeException3 } from "@adonisjs/core/exceptions";
824
+ var AccessTokensLucidUserProvider = class {
825
+ constructor(options) {
826
+ this.options = options;
827
+ }
828
+ /**
829
+ * Reference to the lazily imported model
830
+ */
831
+ model;
832
+ /**
833
+ * Imports the model from the provider, returns and caches it
834
+ * for further operations.
835
+ */
836
+ async getModel() {
837
+ if (this.model) {
838
+ return this.model;
839
+ }
840
+ const importedModel = await this.options.model();
841
+ this.model = importedModel.default;
842
+ return this.model;
843
+ }
844
+ /**
845
+ * Returns the tokens provider associated with the user model
846
+ */
847
+ async getTokensProvider() {
848
+ const model = await this.getModel();
849
+ if (!model[this.options.tokens]) {
850
+ throw new RuntimeException3(
851
+ `Cannot use "${model.name}" model for verifying access tokens. Make sure to assign a token provider to the model.`
852
+ );
853
+ }
854
+ return model[this.options.tokens];
855
+ }
856
+ /**
857
+ * Creates an adapter user for the guard
858
+ */
859
+ async createUserForGuard(user) {
860
+ const model = await this.getModel();
861
+ if (user instanceof model === false) {
862
+ throw new RuntimeException3(
863
+ `Invalid user object. It must be an instance of the "${model.name}" model`
864
+ );
865
+ }
866
+ return {
867
+ getId() {
868
+ if (!user.$primaryKeyValue) {
869
+ throw new RuntimeException3(
870
+ `Cannot use "${model.name}" model for authentication. The value of column "${model.primaryKey}" is undefined or null`
871
+ );
872
+ }
873
+ return user.$primaryKeyValue;
874
+ },
875
+ getOriginal() {
876
+ return user;
877
+ }
878
+ };
879
+ }
880
+ /**
881
+ * Create a token for a given user
882
+ */
883
+ async createToken(user, abilities, options) {
884
+ const tokensProvider = await this.getTokensProvider();
885
+ return tokensProvider.create(user, abilities, options);
886
+ }
887
+ /**
888
+ * Finds a user by the user id
889
+ */
890
+ async findById(identifier) {
891
+ const model = await this.getModel();
892
+ const user = await model.find(identifier);
893
+ if (!user) {
894
+ return null;
895
+ }
896
+ return this.createUserForGuard(user);
897
+ }
898
+ /**
899
+ * Verifies a publicly shared access token and returns an
900
+ * access token for it.
901
+ */
902
+ async verifyToken(tokenValue) {
903
+ const tokensProvider = await this.getTokensProvider();
904
+ return tokensProvider.verify(tokenValue);
905
+ }
906
+ };
907
+
908
+ // modules/access_tokens_guard/define_config.ts
909
+ function tokensGuard(config) {
910
+ return {
911
+ async resolver(name, app) {
912
+ const emitter = await app.container.make("emitter");
913
+ const provider = "resolver" in config.provider ? await config.provider.resolver(app) : config.provider;
914
+ return (ctx) => new AccessTokensGuard(name, ctx, emitter, provider);
915
+ }
916
+ };
917
+ }
918
+ function tokensUserProvider(config) {
919
+ return new AccessTokensLucidUserProvider(config);
920
+ }
921
+ export {
922
+ AccessToken,
923
+ AccessTokensGuard,
924
+ AccessTokensLucidUserProvider,
925
+ DbAccessTokensProvider,
926
+ tokensGuard,
927
+ tokensUserProvider
928
+ };
929
+ //# sourceMappingURL=main.js.map