@solidxai/core 0.1.13-beta.18 → 0.1.13-beta.19
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/CHANGELOG.md +582 -0
- package/dist/config/cache.options.d.ts.map +1 -1
- package/dist/config/cache.options.js +2 -2
- package/dist/config/cache.options.js.map +1 -1
- package/dist/controllers/authentication.controller.d.ts +1 -1
- package/dist/controllers/authentication.controller.d.ts.map +1 -1
- package/dist/controllers/authentication.controller.js +4 -3
- package/dist/controllers/authentication.controller.js.map +1 -1
- package/dist/helpers/solid-microservice-adapter.service.d.ts.map +1 -1
- package/dist/helpers/solid-microservice-adapter.service.js +1 -1
- package/dist/helpers/solid-microservice-adapter.service.js.map +1 -1
- package/dist/interfaces/active-user-data.interface.d.ts +1 -0
- package/dist/interfaces/active-user-data.interface.d.ts.map +1 -1
- package/dist/interfaces/active-user-data.interface.js.map +1 -1
- package/dist/services/api-key.service.d.ts.map +1 -1
- package/dist/services/api-key.service.js +1 -1
- package/dist/services/api-key.service.js.map +1 -1
- package/dist/services/authentication.service.d.ts +5 -4
- package/dist/services/authentication.service.d.ts.map +1 -1
- package/dist/services/authentication.service.js +50 -19
- package/dist/services/authentication.service.js.map +1 -1
- package/dist/services/refresh-token-ids-storage.service.d.ts +25 -6
- package/dist/services/refresh-token-ids-storage.service.d.ts.map +1 -1
- package/dist/services/refresh-token-ids-storage.service.js +80 -42
- package/dist/services/refresh-token-ids-storage.service.js.map +1 -1
- package/package.json +2 -2
- package/src/config/cache.options.ts +9 -1
- package/src/controllers/authentication.controller.ts +5 -2
- package/src/helpers/solid-microservice-adapter.service.ts +6 -1
- package/src/interfaces/active-user-data.interface.ts +9 -0
- package/src/services/api-key.service.ts +13 -1
- package/src/services/authentication.service.ts +127 -36
- package/src/services/refresh-token-ids-storage.service.ts +229 -90
|
@@ -1,21 +1,40 @@
|
|
|
1
1
|
import { Cache } from 'cache-manager';
|
|
2
2
|
import { AuthenticationService } from './authentication.service';
|
|
3
|
+
import { SettingService } from './setting.service';
|
|
3
4
|
export declare class InvalidatedRefreshTokenError extends Error {
|
|
4
5
|
}
|
|
5
6
|
type RefreshTokenState = {
|
|
6
7
|
currentRefreshToken: string;
|
|
7
8
|
previousRefreshToken: string;
|
|
9
|
+
previousValidUntil?: number;
|
|
10
|
+
};
|
|
11
|
+
export type RefreshTokenClaims = {
|
|
12
|
+
deviceKey?: string;
|
|
13
|
+
epoch?: number;
|
|
14
|
+
};
|
|
15
|
+
export type RotatedRefreshToken = {
|
|
16
|
+
refreshToken: string;
|
|
17
|
+
deviceKey?: string;
|
|
8
18
|
};
|
|
9
19
|
export declare class RefreshTokenIdsStorageService {
|
|
10
20
|
private cacheManager;
|
|
11
21
|
private readonly authenticationService;
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
22
|
+
private readonly settingService;
|
|
23
|
+
constructor(cacheManager: Cache, authenticationService: AuthenticationService, settingService: SettingService);
|
|
24
|
+
areConcurrentLoginsAllowed(): boolean;
|
|
25
|
+
insert(userId: number, refreshToken: string, previousRefreshToken?: string, deviceKey?: string): Promise<void>;
|
|
26
|
+
invalidate(userId: number, deviceKey?: string): Promise<void>;
|
|
27
|
+
invalidateAll(userId: number): Promise<void>;
|
|
28
|
+
getEpoch(userId: number): Promise<number | undefined>;
|
|
29
|
+
validateAndRotate(user: any, refreshToken: string, claims?: RefreshTokenClaims): Promise<RotatedRefreshToken>;
|
|
30
|
+
getCurrentRefreshTokenState(userId: number, deviceKey?: string): Promise<RefreshTokenState | undefined>;
|
|
17
31
|
private getKey;
|
|
18
|
-
|
|
32
|
+
private getEpochKey;
|
|
33
|
+
private resolveNextDeviceKey;
|
|
34
|
+
private isEpochCurrent;
|
|
35
|
+
private getStateTtlMs;
|
|
36
|
+
private isRefreshTokenState;
|
|
37
|
+
private isWithinGraceWindow;
|
|
19
38
|
}
|
|
20
39
|
export {};
|
|
21
40
|
//# sourceMappingURL=refresh-token-ids-storage.service.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refresh-token-ids-storage.service.d.ts","sourceRoot":"","sources":["../../src/services/refresh-token-ids-storage.service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"refresh-token-ids-storage.service.d.ts","sourceRoot":"","sources":["../../src/services/refresh-token-ids-storage.service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAGtC,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAGnD,qBAAa,4BAA6B,SAAQ,KAAK;CAAI;AAe3D,KAAK,iBAAiB,GAAG;IACrB,mBAAmB,EAAE,MAAM,CAAC;IAC5B,oBAAoB,EAAE,MAAM,CAAC;IAM7B,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC/B,CAAC;AAQF,MAAM,MAAM,kBAAkB,GAAG;IAC7B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG;IAC9B,YAAY,EAAE,MAAM,CAAC;IAGrB,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF,qBACa,6BAA6B;IAEX,OAAO,CAAC,YAAY;IAE3C,OAAO,CAAC,QAAQ,CAAC,qBAAqB;IACtC,OAAO,CAAC,QAAQ,CAAC,cAAc;gBAHA,YAAY,EAAE,KAAK,EAEjC,qBAAqB,EAAE,qBAAqB,EAC5C,cAAc,EAAE,cAAc;IAenD,0BAA0B,IAAI,OAAO;IAI/B,MAAM,CACR,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM,EACpB,oBAAoB,CAAC,EAAE,MAAM,EAC7B,SAAS,CAAC,EAAE,MAAM,GACnB,OAAO,CAAC,IAAI,CAAC;IAeV,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAa7D,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAc5C,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;IAIrD,iBAAiB,CACnB,IAAI,EAAE,GAAG,EACT,YAAY,EAAE,MAAM,EACpB,MAAM,GAAE,kBAAuB,GAChC,OAAO,CAAC,mBAAmB,CAAC;IAwD/B,2BAA2B,CACvB,MAAM,EAAE,MAAM,EACd,SAAS,CAAC,EAAE,MAAM,GACnB,OAAO,CAAC,iBAAiB,GAAG,SAAS,CAAC;IAIzC,OAAO,CAAC,MAAM;IAMd,OAAO,CAAC,WAAW;IAYnB,OAAO,CAAC,oBAAoB;YAOd,cAAc;IAc5B,OAAO,CAAC,aAAa;IAOrB,OAAO,CAAC,mBAAmB;IAS3B,OAAO,CAAC,mBAAmB;CAoB9B"}
|
|
@@ -15,69 +15,106 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
15
15
|
exports.RefreshTokenIdsStorageService = exports.InvalidatedRefreshTokenError = void 0;
|
|
16
16
|
const cache_manager_1 = require("@nestjs/cache-manager");
|
|
17
17
|
const common_1 = require("@nestjs/common");
|
|
18
|
+
const crypto_1 = require("crypto");
|
|
18
19
|
const authentication_service_1 = require("./authentication.service");
|
|
20
|
+
const setting_service_1 = require("./setting.service");
|
|
19
21
|
class InvalidatedRefreshTokenError extends Error {
|
|
20
22
|
}
|
|
21
23
|
exports.InvalidatedRefreshTokenError = InvalidatedRefreshTokenError;
|
|
24
|
+
const PREVIOUS_TOKEN_GRACE_MS = 60 * 1000;
|
|
25
|
+
const STATE_TTL_BUFFER_SECONDS = 60;
|
|
22
26
|
let RefreshTokenIdsStorageService = class RefreshTokenIdsStorageService {
|
|
23
|
-
constructor(cacheManager, authenticationService) {
|
|
27
|
+
constructor(cacheManager, authenticationService, settingService) {
|
|
24
28
|
this.cacheManager = cacheManager;
|
|
25
29
|
this.authenticationService = authenticationService;
|
|
30
|
+
this.settingService = settingService;
|
|
26
31
|
}
|
|
27
|
-
|
|
32
|
+
areConcurrentLoginsAllowed() {
|
|
33
|
+
return !this.settingService.getConfigValue("preventConcurrentLogins");
|
|
34
|
+
}
|
|
35
|
+
async insert(userId, refreshToken, previousRefreshToken, deviceKey) {
|
|
28
36
|
const refreshTokenState = {
|
|
29
37
|
currentRefreshToken: refreshToken,
|
|
30
38
|
previousRefreshToken: previousRefreshToken ?? "",
|
|
39
|
+
...(previousRefreshToken
|
|
40
|
+
? { previousValidUntil: Date.now() + PREVIOUS_TOKEN_GRACE_MS }
|
|
41
|
+
: {}),
|
|
31
42
|
};
|
|
32
|
-
await this.cacheManager.set(this.getKey(userId), refreshTokenState);
|
|
43
|
+
await this.cacheManager.set(this.getKey(userId, deviceKey), refreshTokenState, this.getStateTtlMs());
|
|
33
44
|
}
|
|
34
|
-
async
|
|
35
|
-
|
|
36
|
-
if (storedId !== refreshToken) {
|
|
37
|
-
throw new InvalidatedRefreshTokenError();
|
|
38
|
-
}
|
|
39
|
-
return storedId === refreshToken;
|
|
45
|
+
async invalidate(userId, deviceKey) {
|
|
46
|
+
await this.cacheManager.del(this.getKey(userId, deviceKey));
|
|
40
47
|
}
|
|
41
|
-
async
|
|
48
|
+
async invalidateAll(userId) {
|
|
49
|
+
const currentEpoch = (await this.getEpoch(userId)) ?? 0;
|
|
50
|
+
await this.cacheManager.set(this.getEpochKey(userId), currentEpoch + 1, this.getStateTtlMs());
|
|
42
51
|
await this.cacheManager.del(this.getKey(userId));
|
|
43
52
|
}
|
|
44
|
-
async
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
});
|
|
62
|
-
}
|
|
63
|
-
}, 1 * 60 * 1000);
|
|
53
|
+
async getEpoch(userId) {
|
|
54
|
+
return (await this.cacheManager.get(this.getEpochKey(userId))) ?? undefined;
|
|
55
|
+
}
|
|
56
|
+
async validateAndRotate(user, refreshToken, claims = {}) {
|
|
57
|
+
const { deviceKey, epoch } = claims;
|
|
58
|
+
const refreshTokenState = await this.cacheManager.get(this.getKey(user.id, deviceKey));
|
|
59
|
+
if (!this.isRefreshTokenState(refreshTokenState)) {
|
|
60
|
+
throw new InvalidatedRefreshTokenError();
|
|
61
|
+
}
|
|
62
|
+
if (deviceKey && !(await this.isEpochCurrent(user.id, epoch))) {
|
|
63
|
+
throw new InvalidatedRefreshTokenError();
|
|
64
|
+
}
|
|
65
|
+
if (refreshTokenState.currentRefreshToken === refreshToken) {
|
|
66
|
+
const nextDeviceKey = this.resolveNextDeviceKey(deviceKey);
|
|
67
|
+
const rotated = await this.authenticationService.generateRefreshToken(user, refreshToken, nextDeviceKey);
|
|
68
|
+
if (nextDeviceKey !== deviceKey) {
|
|
69
|
+
await this.cacheManager.del(this.getKey(user.id, deviceKey));
|
|
64
70
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
71
|
+
return { refreshToken: rotated, deviceKey: nextDeviceKey };
|
|
72
|
+
}
|
|
73
|
+
if (refreshTokenState.previousRefreshToken && refreshTokenState.previousRefreshToken === refreshToken) {
|
|
74
|
+
if (!this.isWithinGraceWindow(refreshTokenState)) {
|
|
75
|
+
throw new InvalidatedRefreshTokenError();
|
|
69
76
|
}
|
|
77
|
+
return { refreshToken: refreshTokenState.currentRefreshToken, deviceKey };
|
|
70
78
|
}
|
|
71
|
-
|
|
72
|
-
|
|
79
|
+
throw new InvalidatedRefreshTokenError();
|
|
80
|
+
}
|
|
81
|
+
getCurrentRefreshTokenState(userId, deviceKey) {
|
|
82
|
+
return this.cacheManager.get(this.getKey(userId, deviceKey));
|
|
83
|
+
}
|
|
84
|
+
getKey(userId, deviceKey) {
|
|
85
|
+
return deviceKey ? `user-${userId}-${deviceKey}` : `user-${userId}`;
|
|
86
|
+
}
|
|
87
|
+
getEpochKey(userId) {
|
|
88
|
+
return `user-epoch-${userId}`;
|
|
89
|
+
}
|
|
90
|
+
resolveNextDeviceKey(deviceKey) {
|
|
91
|
+
if (!this.areConcurrentLoginsAllowed()) {
|
|
92
|
+
return undefined;
|
|
73
93
|
}
|
|
74
|
-
return
|
|
94
|
+
return deviceKey ?? (0, crypto_1.randomUUID)();
|
|
75
95
|
}
|
|
76
|
-
|
|
77
|
-
|
|
96
|
+
async isEpochCurrent(userId, epoch) {
|
|
97
|
+
const storedEpoch = await this.getEpoch(userId);
|
|
98
|
+
if (storedEpoch === undefined) {
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
return epoch === storedEpoch;
|
|
102
|
+
}
|
|
103
|
+
getStateTtlMs() {
|
|
104
|
+
const refreshTokenTtlSeconds = Number(this.settingService.getConfigValue("refreshTokenTtl"));
|
|
105
|
+
return (refreshTokenTtlSeconds + STATE_TTL_BUFFER_SECONDS) * 1000;
|
|
78
106
|
}
|
|
79
|
-
|
|
80
|
-
return
|
|
107
|
+
isRefreshTokenState(state) {
|
|
108
|
+
return (!!state &&
|
|
109
|
+
typeof state === 'object' &&
|
|
110
|
+
'currentRefreshToken' in state &&
|
|
111
|
+
'previousRefreshToken' in state);
|
|
112
|
+
}
|
|
113
|
+
isWithinGraceWindow(state) {
|
|
114
|
+
if (state.previousValidUntil === undefined) {
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
return Date.now() < state.previousValidUntil;
|
|
81
118
|
}
|
|
82
119
|
};
|
|
83
120
|
exports.RefreshTokenIdsStorageService = RefreshTokenIdsStorageService;
|
|
@@ -85,6 +122,7 @@ exports.RefreshTokenIdsStorageService = RefreshTokenIdsStorageService = __decora
|
|
|
85
122
|
(0, common_1.Injectable)(),
|
|
86
123
|
__param(0, (0, common_1.Inject)(cache_manager_1.CACHE_MANAGER)),
|
|
87
124
|
__param(1, (0, common_1.Inject)((0, common_1.forwardRef)(() => authentication_service_1.AuthenticationService))),
|
|
88
|
-
__metadata("design:paramtypes", [Object, authentication_service_1.AuthenticationService
|
|
125
|
+
__metadata("design:paramtypes", [Object, authentication_service_1.AuthenticationService,
|
|
126
|
+
setting_service_1.SettingService])
|
|
89
127
|
], RefreshTokenIdsStorageService);
|
|
90
128
|
//# sourceMappingURL=refresh-token-ids-storage.service.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refresh-token-ids-storage.service.js","sourceRoot":"","sources":["../../src/services/refresh-token-ids-storage.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,yDAAsD;AACtD,2CAAgE;AAEhE,qEAAiE;AAGjE,MAAa,4BAA6B,SAAQ,KAAK;CAAI;AAA3D,oEAA2D;AASpD,IAAM,6BAA6B,GAAnC,MAAM,6BAA6B;IActC,YACmC,YAAmB,EAEjC,qBAA4C;QAF9B,iBAAY,GAAZ,YAAY,CAAO;QAEjC,0BAAqB,GAArB,qBAAqB,CAAuB;IAC7D,CAAC;IAEL,KAAK,CAAC,MAAM,CAAC,MAAc,EAAE,YAAoB,EAAE,oBAA6B;QAC5E,MAAM,iBAAiB,GAAsB;YACzC,mBAAmB,EAAE,YAAY;YACjC,oBAAoB,EAAE,oBAAoB,IAAI,EAAE;SACnD,CAAC;QACF,MAAM,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,iBAAiB,CAAC,CAAC;IACxE,CAAC;IAED,KAAK,CAAC,QAAQ,CAAC,MAAc,EAAE,YAAoB;QAG/C,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,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C,mBAAmB,EAAE,eAAe;4BACpC,oBAAoB,EAAE,EAAE;yBAC3B,CAAC,CAAC;oBACP,CAAC;gBACL,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC;YACtB,CAAC;iBAAM,IAAI,iBAAiB,CAAC,oBAAoB,KAAK,YAAY,EAAE,CAAC;gBAEjE,KAAK,GAAG,IAAI,CAAC;gBAGb,MAAM,yBAAyB,GAAG,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAkC,CAAC;gBACvH,eAAe,GAAG,yBAAyB,EAAE,mBAAmB,CAAC;YACrE,CAAC;QACL,CAAC;QAGD,IAAI,CAAC,KAAK,EAAE,CAAC;YACT,MAAM,IAAI,4BAA4B,EAAE,CAAC;QAC7C,CAAC;QAGD,OAAO,eAAe,CAAC;IAC3B,CAAC;IAEO,MAAM,CAAC,MAAc;QACzB,OAAO,QAAQ,MAAM,EAAE,CAAC;IAC5B,CAAC;IAED,2BAA2B,CAAC,MAAc;QACtC,OAAO,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;IACtD,CAAC;CACJ,CAAA;AArHY,sEAA6B;wCAA7B,6BAA6B;IAFzC,IAAA,mBAAU,GAAE;IAiBJ,WAAA,IAAA,eAAM,EAAC,6BAAa,CAAC,CAAA;IACrB,WAAA,IAAA,eAAM,EAAC,IAAA,mBAAU,EAAC,GAAG,EAAE,CAAC,8CAAqB,CAAC,CAAC,CAAA;6CACR,8CAAqB;GAjBxD,6BAA6B,CAqHzC","sourcesContent":["import { CACHE_MANAGER } from '@nestjs/cache-manager';\nimport { Inject, Injectable, forwardRef } from '@nestjs/common';\nimport { Cache } from 'cache-manager';\nimport { AuthenticationService } from './authentication.service';\n\n// TODO: Ideally this should be in a separate file - putting this here for brevity\nexport class InvalidatedRefreshTokenError extends Error { }\n\ntype RefreshTokenState = {\n currentRefreshToken: string;\n previousRefreshToken: string;\n};\n\n@Injectable()\n// export class RefreshTokenIdsStorageService implements OnApplicationBootstrap, OnApplicationShutdown {\nexport class RefreshTokenIdsStorageService {\n // private redisClient: Redis;\n // onApplicationBootstrap() {\n // // TODO: Ideally, we should move this to the dedicated \"RedisModule\" instead of initiating the connection here.\n // this.redisClient = new Redis({\n // // TODO: According to best practices, we should use the environment variables here instead.\n // host: 'localhost',\n // port: 6379,\n // });\n // }\n // onApplicationShutdown(signal?: string) {\n // return this.redisClient.quit();\n // }\n\n constructor(\n @Inject(CACHE_MANAGER) private cacheManager: Cache,\n @Inject(forwardRef(() => AuthenticationService))\n private readonly authenticationService: AuthenticationService\n ) { }\n\n async insert(userId: number, refreshToken: string, previousRefreshToken?: string): Promise<void> {\n const refreshTokenState: RefreshTokenState = {\n currentRefreshToken: refreshToken,\n previousRefreshToken: previousRefreshToken ?? \"\",\n };\n await this.cacheManager.set(this.getKey(userId), refreshTokenState);\n }\n\n async validate(userId: number, refreshToken: string): Promise<boolean> {\n // TODO: Assume you get this shape out of the cache {\"currentRefreshToken\": \"\", \"previousRefreshToken\": \"\"}\n // Then you will compare against the currentRefreshToken.\n const storedId = await this.cacheManager.get(this.getKey(userId));\n if (storedId !== refreshToken) {\n throw new InvalidatedRefreshTokenError();\n }\n return storedId === refreshToken;\n }\n\n async invalidate(userId: number): Promise<void> {\n await this.cacheManager.del(this.getKey(userId));\n }\n\n async validateAndRotate(user: any, refreshToken: string): Promise<string> {\n let valid = false;\n\n // TODO: Assume you get this shape out of the cache {\"currentRefreshToken\": \"\", \"previousRefreshToken\": \"\"}\n // Then you will compare against the currentRefreshToken.\n const refreshTokenState = await this.cacheManager.get(this.getKey(user.id)) as RefreshTokenState | undefined;\n\n // Use the authentication service to generate a new refresh token, set it in the currentRefreshToken in scenario 1 and return.\n\n // if UI.refresh_token is matching with Cache.currentRefreshToken\n // then invalidate (updated cache state, no need to delete anything), then generate new token and return.\n // also set a setTimeout to run after X minutes, this will simply update the RefreshTokenCacheState to this object {\"currentRefreshToken\": \"R2\",\"justInvalidatedRefreshToken\": \"\"}\n // valid=true\n\n // - if UI.refresh_token is matching Cache.justInvalidatedRefreshToken \n // then use the Cache.currentRefreshToken, generate new access token and return.\n // We do not modify the cache state at all.\n // valid=true\n\n let newRefreshToken: string | undefined;\n if (\n refreshTokenState &&\n typeof refreshTokenState === 'object' &&\n 'currentRefreshToken' in refreshTokenState &&\n 'previousRefreshToken' in refreshTokenState\n ) {\n if (refreshTokenState.currentRefreshToken === refreshToken) {\n // Scenario 1: Token matches currentRefreshToken\n valid = true;\n // Rotate tokens: move current to previous, set new current (simulate generation)\n newRefreshToken = await this.authenticationService.generateRefreshToken(user, refreshTokenState.currentRefreshToken); // Replace with real token generation logic\n\n\n // updated cache state\n // await this.cacheManager.set(this.getKey(user.id), {\n // currentRefreshToken: newRefreshToken,\n // previousRefreshToken: refreshTokenState.currentRefreshToken,\n // });\n\n // Optionally, set a timeout to clear previousRefreshToken after X minutes\n setTimeout(async () => {\n const state = (await this.cacheManager.get(this.getKey(user.id))) as any;\n if (state && state.currentRefreshToken === newRefreshToken) {\n await this.cacheManager.set(this.getKey(user.id), {\n currentRefreshToken: newRefreshToken,\n previousRefreshToken: \"\",\n });\n }\n }, 1 * 60 * 1000); // 5 minutes\n } else if (refreshTokenState.previousRefreshToken === refreshToken) {\n // Scenario 2: Token matches previousRefreshToken\n valid = true;\n // Do not modify cache\n // Generate new refresh token based on currentRefreshToken\n const existingRefreshTokenState = (await this.cacheManager.get(this.getKey(user.id))) as RefreshTokenState | undefined;\n newRefreshToken = existingRefreshTokenState?.currentRefreshToken;\n }\n }\n\n\n if (!valid) {\n throw new InvalidatedRefreshTokenError();\n }\n\n // TODO: return the refresh token either currentRefreshToken\n return newRefreshToken; // Fallback to the provided tokenId if no new token was generated\n }\n\n private getKey(userId: number): string {\n return `user-${userId}`;\n }\n\n getCurrentRefreshTokenState(userId: number): Promise<RefreshTokenState | undefined> {\n return this.cacheManager.get(this.getKey(userId));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"refresh-token-ids-storage.service.js","sourceRoot":"","sources":["../../src/services/refresh-token-ids-storage.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,yDAAsD;AACtD,2CAAgE;AAEhE,mCAAoC;AAEpC,qEAAiE;AACjE,uDAAmD;AAGnD,MAAa,4BAA6B,SAAQ,KAAK;CAAI;AAA3D,oEAA2D;AAO3D,MAAM,uBAAuB,GAAG,EAAE,GAAG,IAAI,CAAC;AAM1C,MAAM,wBAAwB,GAAG,EAAE,CAAC;AAgC7B,IAAM,6BAA6B,GAAnC,MAAM,6BAA6B;IACtC,YACmC,YAAmB,EAEjC,qBAA4C,EAC5C,cAA8B;QAHhB,iBAAY,GAAZ,YAAY,CAAO;QAEjC,0BAAqB,GAArB,qBAAqB,CAAuB;QAC5C,mBAAc,GAAd,cAAc,CAAgB;IAC/C,CAAC;IAcL,0BAA0B;QACtB,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,cAAc,CAAmB,yBAAyB,CAAC,CAAC;IAC5F,CAAC;IAED,KAAK,CAAC,MAAM,CACR,MAAc,EACd,YAAoB,EACpB,oBAA6B,EAC7B,SAAkB;QAElB,MAAM,iBAAiB,GAAsB;YACzC,mBAAmB,EAAE,YAAY;YACjC,oBAAoB,EAAE,oBAAoB,IAAI,EAAE;YAChD,GAAG,CAAC,oBAAoB;gBACpB,CAAC,CAAC,EAAE,kBAAkB,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,uBAAuB,EAAE;gBAC9D,CAAC,CAAC,EAAE,CAAC;SACZ,CAAC;QACF,MAAM,IAAI,CAAC,YAAY,CAAC,GAAG,CACvB,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,EAC9B,iBAAiB,EACjB,IAAI,CAAC,aAAa,EAAE,CACvB,CAAC;IACN,CAAC;IAED,KAAK,CAAC,UAAU,CA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AAE,CAAC,8CAAqB,CAAC,CAAC,CAAA;6CACR,8CAAqB;QAC5B,gCAAc;GAL1C,6BAA6B,CAyNzC","sourcesContent":["import { CACHE_MANAGER } from '@nestjs/cache-manager';\nimport { Inject, Injectable, forwardRef } from '@nestjs/common';\nimport { Cache } from 'cache-manager';\nimport { randomUUID } from 'crypto';\nimport type { SolidCoreSetting } from 'src/services/settings/default-settings-provider.service';\nimport { AuthenticationService } from './authentication.service';\nimport { SettingService } from './setting.service';\n\n// TODO: Ideally this should be in a separate file - putting this here for brevity\nexport class InvalidatedRefreshTokenError extends Error { }\n\n// How long a rotated-out refresh token stays acceptable. This window is the\n// point of keeping a previous token at all: concurrent requests from one user\n// must not break each other. core-ui's single-flight guard is module-level and\n// therefore per tab, so two tabs crossing the refresh threshold together will\n// both present the same token - the second one is served from here.\nconst PREVIOUS_TOKEN_GRACE_MS = 60 * 1000;\n\n// The cache entry must outlive the JWT it holds. If it expired first, refresh\n// would fail with ACCESS_DENIED (InvalidatedRefreshTokenError) rather than the\n// SESSION_EXPIRED that the token's own `exp` produces - the same event\n// reported two different ways.\nconst STATE_TTL_BUFFER_SECONDS = 60;\n\ntype RefreshTokenState = {\n currentRefreshToken: string;\n previousRefreshToken: string;\n // Absolute epoch-ms deadline after which previousRefreshToken is refused.\n // Stored rather than scheduled: an in-process timer is lost when the pod\n // restarts, which used to leave the rotated-out token valid until the next\n // rotation instead of for one minute. Optional because entries written\n // before this field existed will not carry it.\n previousValidUntil?: number;\n};\n\n/**\n * The bucket-identifying claims carried on a refresh token. Absent on tokens\n * issued before per-device sessions existed, and on tokens issued while\n * preventConcurrentLogins is on - which is exactly how the read path tells the\n * two schemes apart without consulting any setting.\n */\nexport type RefreshTokenClaims = {\n deviceKey?: string;\n epoch?: number;\n};\n\nexport type RotatedRefreshToken = {\n refreshToken: string;\n // The bucket the rotated token now lives in. Differs from the incoming\n // deviceKey only when a pre-migration token was just moved into one.\n deviceKey?: string;\n};\n\n@Injectable()\nexport class RefreshTokenIdsStorageService {\n constructor(\n @Inject(CACHE_MANAGER) private cacheManager: Cache,\n @Inject(forwardRef(() => AuthenticationService))\n private readonly authenticationService: AuthenticationService,\n private readonly settingService: SettingService,\n ) { }\n\n /**\n * The inverse of the `preventConcurrentLogins` setting, and the only place\n * it is interpreted.\n *\n * That setting already promises, when off, that sessions may coexist;\n * splitting the refresh-token keyspace per device is what finally delivers\n * it. When it is on, its stated purpose is a single live session, so\n * per-device keys would be meaningless and the original single slot is kept.\n *\n * This governs the WRITE path only. Reads always branch on the token's own\n * claim, so toggling the setting never invalidates a live session.\n */\n areConcurrentLoginsAllowed(): boolean {\n return !this.settingService.getConfigValue<SolidCoreSetting>(\"preventConcurrentLogins\");\n }\n\n async insert(\n userId: number,\n refreshToken: string,\n previousRefreshToken?: string,\n deviceKey?: string,\n ): Promise<void> {\n const refreshTokenState: RefreshTokenState = {\n currentRefreshToken: refreshToken,\n previousRefreshToken: previousRefreshToken ?? \"\",\n ...(previousRefreshToken\n ? { previousValidUntil: Date.now() + PREVIOUS_TOKEN_GRACE_MS }\n : {}),\n };\n await this.cacheManager.set(\n this.getKey(userId, deviceKey),\n refreshTokenState,\n this.getStateTtlMs(),\n );\n }\n\n async invalidate(userId: number, deviceKey?: string): Promise<void> {\n await this.cacheManager.del(this.getKey(userId, deviceKey));\n }\n\n /**\n * Bulk invalidation - \"log out everywhere\", and the right hook for password\n * change or forced deactivation.\n *\n * Per-device buckets cannot be enumerated through cache-manager, so this\n * bumps a per-user epoch that every per-device token carries as a claim.\n * One write invalidates every outstanding token without a scan and without\n * the read-modify-write race an index of device keys would have.\n */\n async invalidateAll(userId: number): Promise<void> {\n const currentEpoch = (await this.getEpoch(userId)) ?? 0;\n await this.cacheManager.set(\n this.getEpochKey(userId),\n currentEpoch + 1,\n // Outlives every bucket that could hold a pre-bump token: those were\n // written earlier, so they expire no later than this key does.\n this.getStateTtlMs(),\n );\n // Single-slot mode and pre-migration entries live under the bare key,\n // which carries no epoch claim - delete it directly.\n await this.cacheManager.del(this.getKey(userId));\n }\n\n async getEpoch(userId: number): Promise<number | undefined> {\n return (await this.cacheManager.get<number>(this.getEpochKey(userId))) ?? undefined;\n }\n\n async validateAndRotate(\n user: any,\n refreshToken: string,\n claims: RefreshTokenClaims = {},\n ): Promise<RotatedRefreshToken> {\n const { deviceKey, epoch } = claims;\n\n // The read key comes from the token's own claim, never from a setting.\n // A token issued under either scheme therefore stays valid when\n // preventConcurrentLogins is toggled - in both directions - and a\n // pre-migration token still finds the bare key it was written to.\n const refreshTokenState = await this.cacheManager.get(\n this.getKey(user.id, deviceKey),\n ) as RefreshTokenState | undefined;\n\n if (!this.isRefreshTokenState(refreshTokenState)) {\n throw new InvalidatedRefreshTokenError();\n }\n\n if (deviceKey && !(await this.isEpochCurrent(user.id, epoch))) {\n throw new InvalidatedRefreshTokenError();\n }\n\n // Scenario 1: the live token. Rotate it. generateRefreshToken calls\n // insert(), which writes the new state and stamps the grace deadline\n // onto the token being rotated out.\n if (refreshTokenState.currentRefreshToken === refreshToken) {\n const nextDeviceKey = this.resolveNextDeviceKey(deviceKey);\n const rotated = await this.authenticationService.generateRefreshToken(\n user,\n refreshToken,\n nextDeviceKey,\n );\n\n if (nextDeviceKey !== deviceKey) {\n // The session changed buckets - either migrating out of the\n // pre-deploy single slot, or collapsing back into it because\n // preventConcurrentLogins was switched on. The new state is\n // already written; drop the key it came from so nothing is\n // left behind.\n await this.cacheManager.del(this.getKey(user.id, deviceKey));\n }\n\n return { refreshToken: rotated, deviceKey: nextDeviceKey };\n }\n\n // Scenario 2: the token just rotated out. This is the concurrent-request\n // case the previous slot exists for - a second in-flight request that\n // was issued the old token before the first one rotated it. Hand back\n // the live token so it succeeds, provided the grace window is still open.\n if (refreshTokenState.previousRefreshToken && refreshTokenState.previousRefreshToken === refreshToken) {\n if (!this.isWithinGraceWindow(refreshTokenState)) {\n throw new InvalidatedRefreshTokenError();\n }\n return { refreshToken: refreshTokenState.currentRefreshToken, deviceKey };\n }\n\n throw new InvalidatedRefreshTokenError();\n }\n\n getCurrentRefreshTokenState(\n userId: number,\n deviceKey?: string,\n ): Promise<RefreshTokenState | undefined> {\n return this.cacheManager.get(this.getKey(userId, deviceKey));\n }\n\n private getKey(userId: number, deviceKey?: string): string {\n return deviceKey ? `user-${userId}-${deviceKey}` : `user-${userId}`;\n }\n\n // Deliberately not `user-${userId}-epoch`, which a device key of the\n // literal string \"epoch\" would collide with.\n private getEpochKey(userId: number): string {\n return `user-epoch-${userId}`;\n }\n\n /**\n * Which bucket a rotated token should land in. The setting is consulted\n * first so that turning preventConcurrentLogins ON collapses existing\n * per-device sessions back into the single slot on their next refresh -\n * where normal last-login-wins applies, which is what that setting means.\n * Leaving them in their own buckets would keep concurrent sessions alive\n * while the setting claimed to forbid them.\n */\n private resolveNextDeviceKey(deviceKey?: string): string | undefined {\n if (!this.areConcurrentLoginsAllowed()) {\n return undefined;\n }\n return deviceKey ?? randomUUID();\n }\n\n private async isEpochCurrent(userId: number, epoch?: number): Promise<boolean> {\n const storedEpoch = await this.getEpoch(userId);\n // Nothing has ever been bulk-invalidated for this user - or the cache\n // was flushed, in which case every bucket is gone and the token is\n // already dead by the read above. Either way, accept.\n if (storedEpoch === undefined) {\n return true;\n }\n return epoch === storedEpoch;\n }\n\n // cache-manager v5 expects milliseconds; refreshTokenTtl is configured in\n // seconds. Without an explicit TTL these entries never expire - neither\n // cache path supplies a default - and the keyspace grows without bound.\n private getStateTtlMs(): number {\n const refreshTokenTtlSeconds = Number(\n this.settingService.getConfigValue<SolidCoreSetting>(\"refreshTokenTtl\"),\n );\n return (refreshTokenTtlSeconds + STATE_TTL_BUFFER_SECONDS) * 1000;\n }\n\n private isRefreshTokenState(state: unknown): state is RefreshTokenState {\n return (\n !!state &&\n typeof state === 'object' &&\n 'currentRefreshToken' in state &&\n 'previousRefreshToken' in state\n );\n }\n\n private isWithinGraceWindow(state: RefreshTokenState): boolean {\n // TRANSITIONAL - safe to delete one refreshTokenTtl after this ships.\n //\n // Entries written before previousValidUntil existed carry no deadline\n // to test. They are accepted so that the deploy rejects nobody: a tab\n // that legitimately rotated moments earlier keeps working. The cost is\n // that for such an entry the previous token stays acceptable until its\n // own JWT `exp` rather than for 60s - which is exactly how the old code\n // already behaved whenever its in-process timer was lost to a restart,\n // so this is an unfixed pre-existing case, not a new one.\n //\n // It self-heals: the user's next rotation writes a new-format state\n // with a deadline. Once every pre-deploy entry has rotated or expired\n // (one refreshTokenTtl), this branch is unreachable - drop it, and the\n // undefined case becomes a rejection.\n if (state.previousValidUntil === undefined) {\n return true;\n }\n return Date.now() < state.previousValidUntil;\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@solidxai/core",
|
|
3
|
-
"version": "0.1.13-beta.
|
|
3
|
+
"version": "0.1.13-beta.19",
|
|
4
4
|
"description": "This module is a NestJS module containing all the required core providers required by a Solid application",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"bcrypt": "^5.1.1",
|
|
46
46
|
"bson": "^6.10.1",
|
|
47
47
|
"cache-manager": "^5.5.2",
|
|
48
|
-
"cache-manager-redis-
|
|
48
|
+
"cache-manager-redis-yet": "^5.1.5",
|
|
49
49
|
"class-transformer": "^0.5.1",
|
|
50
50
|
"class-validator": "^0.14.1",
|
|
51
51
|
"cron-parser": "^5.5.0",
|
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import { CacheModuleAsyncOptions } from '@nestjs/cache-manager';
|
|
2
2
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
|
3
|
-
|
|
3
|
+
// cache-manager-redis-yet, not cache-manager-redis-store. The latter stops at
|
|
4
|
+
// 3.0.1 and implements the cache-manager v4 store contract: it expects an
|
|
5
|
+
// options object and reads `options.ttl` in seconds. cache-manager v5 calls
|
|
6
|
+
// `store.set(key, value, ttl)` with a bare number of milliseconds, so that
|
|
7
|
+
// store found no `.ttl`, fell back to an unset default, and issued a plain
|
|
8
|
+
// `SET` - silently discarding every TTL passed anywhere in the app and leaving
|
|
9
|
+
// Redis keys that never expire. redis-yet implements the v5 contract and
|
|
10
|
+
// writes with `PX`, so millisecond TTLs land correctly.
|
|
11
|
+
import { redisStore } from 'cache-manager-redis-yet';
|
|
4
12
|
import { isRedisConfigured } from 'src/helpers/environment.helper';
|
|
5
13
|
|
|
6
14
|
export const CacheManagerOptions: CacheModuleAsyncOptions = {
|
|
@@ -107,8 +107,11 @@ export class AuthenticationController {
|
|
|
107
107
|
@Post('logout')
|
|
108
108
|
@Public()
|
|
109
109
|
@HttpCode(HttpStatus.OK)
|
|
110
|
-
async logout(
|
|
111
|
-
|
|
110
|
+
async logout(
|
|
111
|
+
@Body('refreshToken') refreshToken: string,
|
|
112
|
+
@Body('allDevices') allDevices?: boolean,
|
|
113
|
+
) {
|
|
114
|
+
return this.authService.logout(refreshToken, allDevices === true);
|
|
112
115
|
}
|
|
113
116
|
|
|
114
117
|
@ApiBearerAuth("jwt")
|
|
@@ -79,7 +79,12 @@ export class SolidMicroserviceAdapter {
|
|
|
79
79
|
const responseData = response.data as SolidxIamAuthResponse;
|
|
80
80
|
const ttlSeconds = this.getJwtTtlSeconds(responseData?.data?.accessToken);
|
|
81
81
|
if (ttlSeconds && ttlSeconds > 0) {
|
|
82
|
-
|
|
82
|
+
// cache-manager v5 expects milliseconds. This previously passed seconds,
|
|
83
|
+
// which the old Redis store discarded outright - so the entry simply
|
|
84
|
+
// never expired. Now that TTLs are honoured, passing seconds unconverted
|
|
85
|
+
// would expire the cached token ~1000x too early and re-authenticate
|
|
86
|
+
// against IAM on nearly every call.
|
|
87
|
+
await this.cacheManager.set(cacheKey, responseData, ttlSeconds * 1000);
|
|
83
88
|
}
|
|
84
89
|
|
|
85
90
|
return responseData;
|
|
@@ -22,6 +22,15 @@ export interface ActiveUserData {
|
|
|
22
22
|
*/
|
|
23
23
|
sessionId?: string;
|
|
24
24
|
|
|
25
|
+
/**
|
|
26
|
+
* Identifies which per-device refresh-token bucket this session belongs to.
|
|
27
|
+
* Present only while concurrent logins are permitted; mutually exclusive with
|
|
28
|
+
* sessionId, which exists only when they are not. Carried on the access token
|
|
29
|
+
* so bearer-authenticated endpoints that need this session's refresh token
|
|
30
|
+
* can find it.
|
|
31
|
+
*/
|
|
32
|
+
deviceKey?: string;
|
|
33
|
+
|
|
25
34
|
/**
|
|
26
35
|
* The subject's (user) roles.
|
|
27
36
|
* These are part of the JWT token, we simply decode them.
|
|
@@ -131,7 +131,19 @@ export class ApiKeyService {
|
|
|
131
131
|
|
|
132
132
|
const user = apiKeyRecord.user;
|
|
133
133
|
|
|
134
|
-
|
|
134
|
+
// Keyed on the API key record so every call for this key reuses one
|
|
135
|
+
// refresh-token bucket. Without it each call mints a fresh key and
|
|
136
|
+
// therefore a new bucket with a refreshTokenTtl lifetime - a client
|
|
137
|
+
// polling this endpoint would accumulate them without bound.
|
|
138
|
+
//
|
|
139
|
+
// The consequence is that replicas sharing one API key share one
|
|
140
|
+
// bucket and invalidate each other, which is exactly the behaviour
|
|
141
|
+
// before per-device sessions existed, and is benign here: an API key
|
|
142
|
+
// is a permanent credential, so a failed refresh just re-mints.
|
|
143
|
+
const tokens = await this.authenticationService.generateTokens(
|
|
144
|
+
user,
|
|
145
|
+
`apikey-${apiKeyRecord.id}`,
|
|
146
|
+
);
|
|
135
147
|
|
|
136
148
|
|
|
137
149
|
return {
|