@stonyx/oauth 0.1.1-beta.2 → 0.1.1-beta.200

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 (41) hide show
  1. package/README.md +193 -2
  2. package/dist/auth-request.d.ts +147 -0
  3. package/dist/auth-request.js +247 -0
  4. package/dist/main.d.ts +121 -0
  5. package/dist/main.js +194 -0
  6. package/dist/oauth-flow.d.ts +30 -0
  7. package/dist/oauth-flow.js +83 -0
  8. package/dist/providers/discord.d.ts +30 -0
  9. package/dist/providers/discord.js +43 -0
  10. package/dist/session-manager.d.ts +20 -0
  11. package/dist/session-manager.js +30 -0
  12. package/dist/ticket-store.d.ts +134 -0
  13. package/dist/ticket-store.js +140 -0
  14. package/dist/token-manager.d.ts +15 -0
  15. package/dist/token-manager.js +24 -0
  16. package/package.json +45 -8
  17. package/src/auth-request.ts +348 -0
  18. package/src/main.ts +259 -0
  19. package/src/{oauth-flow.js → oauth-flow.ts} +31 -7
  20. package/src/providers/{discord.js → discord.ts} +29 -3
  21. package/src/{session-manager.js → session-manager.ts} +19 -6
  22. package/src/ticket-store.ts +158 -0
  23. package/src/token-manager.ts +35 -0
  24. package/src/types/node.d.ts +19 -0
  25. package/src/types/stonyx-events.d.ts +4 -0
  26. package/src/types/stonyx-rest-server.d.ts +11 -0
  27. package/src/types/stonyx.d.ts +38 -0
  28. package/.github/workflows/ci.yml +0 -16
  29. package/.github/workflows/publish.yml +0 -51
  30. package/src/auth-request.js +0 -74
  31. package/src/main.js +0 -79
  32. package/src/token-manager.js +0 -26
  33. package/test/config/environment.js +0 -18
  34. package/test/integration/oauth-test.js +0 -149
  35. package/test/sample/providers/mock.js +0 -40
  36. package/test/sample/requests/.gitkeep +0 -0
  37. package/test/unit/oauth-flow-test.js +0 -137
  38. package/test/unit/providers/discord-test.js +0 -115
  39. package/test/unit/session-manager-test.js +0 -85
  40. package/test/unit/state-validation-test.js +0 -118
  41. package/test/unit/token-manager-test.js +0 -76
@@ -1,7 +1,33 @@
1
1
  import OAuthFlow from '../oauth-flow.js';
2
+ import type { TokenResult } from '../oauth-flow.js';
3
+
4
+ interface DiscordProviderConfig {
5
+ clientId: string;
6
+ clientSecret: string;
7
+ redirectUri: string;
8
+ scopes?: string[];
9
+ [key: string]: unknown;
10
+ }
11
+
12
+ interface DiscordUser {
13
+ id: string;
14
+ username: string;
15
+ global_name?: string;
16
+ avatar: string | null;
17
+ email?: string | null;
18
+ }
19
+
20
+ interface NormalizedDiscordUser {
21
+ id: string;
22
+ username: string;
23
+ displayName: string;
24
+ avatar: string | null;
25
+ email: string | null;
26
+ raw: DiscordUser;
27
+ }
2
28
 
3
29
  export default class DiscordProvider extends OAuthFlow {
4
- constructor(config) {
30
+ constructor(config: DiscordProviderConfig) {
5
31
  super({
6
32
  ...config,
7
33
  authorizationUrl: 'https://discord.com/oauth2/authorize',
@@ -10,7 +36,7 @@ export default class DiscordProvider extends OAuthFlow {
10
36
  });
11
37
  }
12
38
 
13
- async exchangeCode(code) {
39
+ async exchangeCode(code: string): Promise<TokenResult> {
14
40
  const response = await fetch(this.tokenUrl, {
15
41
  method: 'POST',
16
42
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
@@ -34,7 +60,7 @@ export default class DiscordProvider extends OAuthFlow {
34
60
  };
35
61
  }
36
62
 
37
- normalizeUser(rawUser) {
63
+ override normalizeUser(rawUser: DiscordUser): NormalizedDiscordUser {
38
64
  const { id, username, global_name, avatar, email } = rawUser;
39
65
 
40
66
  return {
@@ -1,13 +1,26 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
 
3
+ interface SessionData {
4
+ user: unknown;
5
+ tokens: unknown;
6
+ expiresAt: number;
7
+ }
8
+
9
+ export interface SessionResult {
10
+ sessionId: string;
11
+ user: unknown;
12
+ expiresAt: number;
13
+ }
14
+
3
15
  export default class SessionManager {
4
- sessions = new Map();
16
+ sessions = new Map<string, SessionData>();
17
+ duration: number;
5
18
 
6
- constructor(duration) {
19
+ constructor(duration: number) {
7
20
  this.duration = duration;
8
21
  }
9
22
 
10
- create(user, tokens) {
23
+ create(user: unknown, tokens: unknown): SessionResult {
11
24
  const sessionId = randomUUID();
12
25
  const expiresAt = Date.now() + (this.duration * 1000);
13
26
 
@@ -16,15 +29,15 @@ export default class SessionManager {
16
29
  return { sessionId, user, expiresAt };
17
30
  }
18
31
 
19
- get(sessionId) {
32
+ get(sessionId: string): SessionData | null {
20
33
  return this.sessions.get(sessionId) || null;
21
34
  }
22
35
 
23
- destroy(sessionId) {
36
+ destroy(sessionId: string): void {
24
37
  this.sessions.delete(sessionId);
25
38
  }
26
39
 
27
- validate(sessionId) {
40
+ validate(sessionId: string): unknown {
28
41
  const session = this.get(sessionId);
29
42
  if (!session) return null;
30
43
 
@@ -0,0 +1,158 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+
3
+ /**
4
+ * Lifetime of an exchange ticket.
5
+ *
6
+ * Sized for one redirect plus one page load, and deliberately two orders of
7
+ * magnitude tighter than the 10-minute state TTL: the ticket is a bearer value
8
+ * travelling in a URL, and the whole point of #45 is that a bearer value in a
9
+ * URL must not be long-lived — in the fragment, so it reaches no server, but
10
+ * still into browser history and readable by scripts on the landing page.
11
+ */
12
+ export const TICKET_TTL_MS = 60 * 1000;
13
+
14
+ /** Entropy of a ticket, in bytes. */
15
+ export const TICKET_BYTES = 32;
16
+
17
+ interface TicketRecord {
18
+ sessionId: string;
19
+ expiresAt: number;
20
+ createdAt: number;
21
+ }
22
+
23
+ export interface RedeemedTicket {
24
+ sessionId: string;
25
+ expiresAt: number;
26
+ }
27
+
28
+ /**
29
+ * Single-use, short-lived tickets that stand in for a session id on the wire.
30
+ *
31
+ * The callback redirect hands the browser a ticket instead of the session id
32
+ * (#45), in the URL *fragment*, which no user agent transmits to any server.
33
+ * The ticket authenticates nothing — `GET /auth` reads the `session-id` header
34
+ * and knows only about `SessionManager` — so a ticket observed in history or
35
+ * by a script reading `location.hash` is worth something only inside the
36
+ * sub-second window before the landing page redeems it, and nothing at all
37
+ * afterwards.
38
+ *
39
+ * Known residual, stated rather than papered over: a ticket observed *within*
40
+ * that window is redeemable by the observer, because nothing here binds a
41
+ * ticket to the client that started the flow. Closing it means binding the way
42
+ * #36 bound the state, and that binding has to travel on a cookie the
43
+ * cross-origin exchange cannot carry.
44
+ *
45
+ * The blocker is `abofs/stonyx-rest-server#63`: `@stonyx/rest-server` calls
46
+ * `cors({ origin, methods })` and has no `credentials` support at all. It is
47
+ * *not* `abofs/stonyx-rest-server#45` — that issue is the response-header half
48
+ * and is already worked around in `auth-request.ts`, which sets and clears the
49
+ * binding cookie on a redirect by reaching through `req.res`. Closing #45
50
+ * would not make this residual closeable. It is a reduction, not an
51
+ * elimination.
52
+ *
53
+ * Like `OAuth.pendingStates`, an abandoned ticket is never collected. That is
54
+ * a pre-existing pattern in this module, not something this store introduces,
55
+ * and it is bounded here by a 60-second TTL rather than a 10-minute one.
56
+ * Tracked, with both maps named, at `abofs/stonyx-oauth#43`.
57
+ *
58
+ * ---
59
+ *
60
+ * **Why this is a second store rather than a reuse of `OAuth.pendingStates`.**
61
+ *
62
+ * The duplication is real and is not an oversight: `pendingStates` is also a
63
+ * single-use, TTL-bounded, consume-on-recognition map keyed by a
64
+ * `randomBytes`-minted opaque token, with the same delete-before-TTL-check
65
+ * ordering and the same never-collected caveat. The shared shape could be
66
+ * extracted into one primitive, and the two constants homes (`STATE_TTL_MS`
67
+ * and `BINDING_VALUE_BYTES` in `main.ts`, `TICKET_TTL_MS` and `TICKET_BYTES`
68
+ * here) could then live together.
69
+ *
70
+ * It is deliberately not done in the change that fixes #45. Widening a
71
+ * security fix into a refactor of the CSRF store means the #36 binding
72
+ * mechanism — whose invariants are load-bearing and separately guarded — moves
73
+ * in the same commit as the fix, for no security gain in either. The two also
74
+ * do not have the same invariants: `pendingStates` is a security control fed
75
+ * by an unauthenticated `GET`, holding a *digest* of a client secret, with a
76
+ * 10-minute budget sized for a provider round trip; this is a delivery
77
+ * convenience reachable only after a successfully bound callback, holding a
78
+ * value it hands back, with a 60-second budget sized for a page load.
79
+ * Collapsing them would couple the control to the convenience.
80
+ *
81
+ * The extraction is tracked at `abofs/stonyx-oauth#58`.
82
+ */
83
+ export default class TicketStore {
84
+ /**
85
+ * Live tickets, keyed by the **SHA-256 of the ticket**, never by the ticket.
86
+ *
87
+ * Keying by the digest means the map holds no redeemable *ticket*: a ticket
88
+ * is a client-presented secret looked up server-side, so what a reader of
89
+ * this map gets is a digest, and a digest cannot be presented to `redeem`.
90
+ *
91
+ * That does not make the map safe to expose. The record *value* holds a
92
+ * plaintext, live `sessionId` — the 24-hour bearer credential this store
93
+ * exists to keep out of URLs — so a heap dump, a debug serialisation or an
94
+ * accidental log of this map yields live session ids. The map is sensitive
95
+ * on that basis and must not be dumped or logged. Whether the stored
96
+ * `sessionId` should itself be protected is a separate question, and is not
97
+ * settled here.
98
+ *
99
+ * This is the mirror image of `OAuth.pendingStates`, not the same shape:
100
+ * there the *key* is the plaintext state token and the digest
101
+ * (`bindingHash`) sits in the value, so that record unlocks nothing on its
102
+ * own; here the digest is the key and the value is a live credential. What
103
+ * the two stores share is the discipline of never keeping a
104
+ * client-presented secret in the clear — neither the ticket nor the binding
105
+ * value is on the heap — but they place the digest on opposite sides of the
106
+ * entry.
107
+ *
108
+ * No constant-time comparison is needed and none is used: lookup is a hash
109
+ * probe on a 256-bit high-entropy key, not a secret-dependent byte
110
+ * comparison, so there is no early-exit timing signal to exploit. That is
111
+ * the same reason `redeem` can stay an ordinary `Map.get`.
112
+ */
113
+ tickets = new Map<string, TicketRecord>();
114
+ ttl = TICKET_TTL_MS;
115
+
116
+ /** SHA-256 of a ticket, hex — the only form of the *ticket* this store keeps. */
117
+ static hash(ticket: string): string {
118
+ return createHash('sha256').update(ticket).digest('hex');
119
+ }
120
+
121
+ /**
122
+ * Mints a ticket for a freshly created session.
123
+ *
124
+ * The ticket is independent entropy, never a transform of the session id:
125
+ * anything derived from the credential is the credential.
126
+ */
127
+ issue(sessionId: string, expiresAt: number): string {
128
+ const ticket = randomBytes(TICKET_BYTES).toString('base64url');
129
+ this.tickets.set(TicketStore.hash(ticket), { sessionId, expiresAt, createdAt: Date.now() });
130
+ return ticket;
131
+ }
132
+
133
+ /**
134
+ * Spends a ticket, if it is live.
135
+ *
136
+ * Consumed on recognition, *before* the TTL check, for the same reason
137
+ * `OAuth.handleCallback` consumes a pending state before validating its
138
+ * binding: every ticket gets exactly one attempt whatever the outcome, so
139
+ * this endpoint is never a repeatable oracle. Deleting after the TTL check
140
+ * instead would leave an expired ticket in the map answering `400` forever
141
+ * while a live one answers `200` — an unauthenticated distinguisher.
142
+ *
143
+ * Returns `null` for unknown, spent and expired tickets alike. The caller
144
+ * maps all three to the same `400`; telling them apart is information the
145
+ * holder of a ticket they did not mint has no business having.
146
+ */
147
+ redeem(ticket: string): RedeemedTicket | null {
148
+ const key = ticket ? TicketStore.hash(ticket) : null;
149
+ const record = key ? this.tickets.get(key) : undefined;
150
+ if (!record) return null;
151
+
152
+ this.tickets.delete(key!);
153
+
154
+ if (Date.now() - record.createdAt > this.ttl) return null;
155
+
156
+ return { sessionId: record.sessionId, expiresAt: record.expiresAt };
157
+ }
158
+ }
@@ -0,0 +1,35 @@
1
+ import type OAuthFlow from './oauth-flow.js';
2
+ import type { TokenResult } from './oauth-flow.js';
3
+
4
+ export interface TokenData extends TokenResult {
5
+ expiresAt: number;
6
+ }
7
+
8
+ export default class TokenManager {
9
+ flow: OAuthFlow;
10
+
11
+ constructor(flow: OAuthFlow) {
12
+ this.flow = flow;
13
+ }
14
+
15
+ async getTokens(code: string): Promise<TokenData> {
16
+ const tokens = await this.flow.exchangeCode(code) as TokenData;
17
+ tokens.expiresAt = Date.now() + (tokens.expiresIn * 1000);
18
+ return tokens;
19
+ }
20
+
21
+ async refresh(refreshToken: string): Promise<TokenData> {
22
+ const tokens = await this.flow.refreshAccessToken(refreshToken) as TokenData;
23
+ tokens.expiresAt = Date.now() + (tokens.expiresIn * 1000);
24
+ return tokens;
25
+ }
26
+
27
+ async revoke(accessToken: string): Promise<void> {
28
+ return this.flow.revokeToken(accessToken);
29
+ }
30
+
31
+ isExpired(tokenData: { expiresAt?: number } | null | undefined): boolean {
32
+ if (!tokenData?.expiresAt) return true;
33
+ return Date.now() >= tokenData.expiresAt;
34
+ }
35
+ }
@@ -0,0 +1,19 @@
1
+ declare module 'node:crypto' {
2
+ export function randomUUID(): string;
3
+
4
+ /**
5
+ * Structural stand-ins: this repo declares its own node shims rather than
6
+ * depending on `@types/node`, so only the surface actually used is typed.
7
+ */
8
+ interface BinaryLike {
9
+ toString(encoding: string): string;
10
+ }
11
+
12
+ interface Hash {
13
+ update(data: string): Hash;
14
+ digest(encoding: string): string;
15
+ }
16
+
17
+ export function randomBytes(size: number): BinaryLike;
18
+ export function createHash(algorithm: string): Hash;
19
+ }
@@ -0,0 +1,4 @@
1
+ declare module '@stonyx/events' {
2
+ export function setup(events: string[]): void;
3
+ export function emit(event: string, ...args: unknown[]): Promise<void>;
4
+ }
@@ -0,0 +1,11 @@
1
+ declare module '@stonyx/rest-server' {
2
+ export class Request {
3
+ constructor();
4
+ }
5
+
6
+ export default class RestServer {
7
+ static instance: RestServer;
8
+ static close(): void;
9
+ mountRoute(RequestClass: unknown, options: { name: string; options?: unknown }): void;
10
+ }
11
+ }
@@ -0,0 +1,38 @@
1
+ declare module 'stonyx/config' {
2
+ interface OAuthConfig {
3
+ providers: Record<string, { module?: string; [key: string]: unknown }>;
4
+ sessionDuration: number;
5
+ frontendCallbackUrl?: string;
6
+ logColor?: string;
7
+ logMethod?: string;
8
+ }
9
+ interface Config {
10
+ oauth: OAuthConfig;
11
+ rootPath: string;
12
+ [key: string]: unknown;
13
+ }
14
+ const config: Config;
15
+ export default config;
16
+ }
17
+
18
+ declare module 'stonyx/log' {
19
+ interface Log {
20
+ oauth(message: string): void;
21
+ error(message: string): void;
22
+ defineType(type: string, setting: string, options?: Record<string, unknown> | null): void;
23
+ [key: string]: unknown;
24
+ }
25
+ const log: Log;
26
+ export default log;
27
+ }
28
+
29
+ declare module 'stonyx' {
30
+ export function waitForModule(name: string): Promise<void>;
31
+ }
32
+
33
+ declare module 'stonyx/test-helpers' {
34
+ export function setupIntegrationTests(hooks: {
35
+ before(fn: () => void | Promise<void>): void;
36
+ after(fn: () => void | Promise<void>): void;
37
+ }): void;
38
+ }
@@ -1,16 +0,0 @@
1
- name: CI
2
-
3
- on:
4
- pull_request:
5
- branches: [dev, main]
6
-
7
- concurrency:
8
- group: ci-${{ github.head_ref || github.ref }}
9
- cancel-in-progress: true
10
-
11
- permissions:
12
- contents: read
13
-
14
- jobs:
15
- test:
16
- uses: abofs/stonyx-workflows/.github/workflows/ci.yml@main
@@ -1,51 +0,0 @@
1
- name: Publish to NPM
2
-
3
- on:
4
- repository_dispatch:
5
- types: [cascade-publish]
6
- workflow_dispatch:
7
- inputs:
8
- version-type:
9
- description: 'Version type'
10
- required: true
11
- type: choice
12
- options:
13
- - patch
14
- - minor
15
- - major
16
- custom-version:
17
- description: 'Custom version (optional, overrides version-type)'
18
- required: false
19
- type: string
20
- pull_request:
21
- types: [opened, synchronize, reopened]
22
- branches: [main]
23
- push:
24
- branches: [main]
25
-
26
- concurrency:
27
- group: ${{ github.event_name == 'repository_dispatch' && 'cascade-update' || format('publish-{0}', github.ref) }}
28
- cancel-in-progress: false
29
-
30
- permissions:
31
- contents: write
32
- id-token: write
33
- pull-requests: write
34
-
35
- jobs:
36
- publish:
37
- if: "!contains(github.event.head_commit.message, '[skip ci]')"
38
- uses: abofs/stonyx-workflows/.github/workflows/npm-publish.yml@main
39
- with:
40
- version-type: ${{ github.event.inputs.version-type }}
41
- custom-version: ${{ github.event.inputs.custom-version }}
42
- cascade-source: ${{ github.event.client_payload.source_package || '' }}
43
- secrets: inherit
44
-
45
- cascade:
46
- needs: publish
47
- uses: abofs/stonyx-workflows/.github/workflows/cascade.yml@main
48
- with:
49
- package-name: ${{ needs.publish.outputs.package-name }}
50
- published-version: ${{ needs.publish.outputs.published-version }}
51
- secrets: inherit
@@ -1,74 +0,0 @@
1
- import { Request } from '@stonyx/rest-server';
2
-
3
- export default class AuthRequest extends Request {
4
- constructor(oauth) {
5
- super();
6
- this.oauth = oauth;
7
- }
8
-
9
- handlers = {
10
- get: {
11
- '/': ({ headers }) => {
12
- const sessionId = headers['session-id'];
13
- if (!sessionId) return 401;
14
-
15
- const user = this.oauth.getSession(sessionId);
16
- if (!user) return 401;
17
-
18
- return user;
19
- },
20
-
21
- '/login/:provider': (req, state) => {
22
- const { provider: providerName } = req.params;
23
-
24
- try {
25
- const url = this.oauth.getAuthorizationUrl(providerName);
26
- state.redirect = url;
27
- } catch {
28
- return 404;
29
- }
30
- },
31
-
32
- '/callback/:provider': async (req, state) => {
33
- const { provider: providerName } = req.params;
34
- const { code, state: stateToken, error } = req.query;
35
-
36
- if (error) {
37
- if (this.oauth.frontendCallbackUrl) {
38
- state.redirect = `${this.oauth.frontendCallbackUrl}?error=${encodeURIComponent(error)}`;
39
- return;
40
- }
41
- return 400;
42
- }
43
-
44
- if (!code) return 400;
45
-
46
- try {
47
- const session = await this.oauth.handleCallback(providerName, code, stateToken);
48
-
49
- if (this.oauth.frontendCallbackUrl) {
50
- const params = new URLSearchParams({
51
- sessionId: session.sessionId,
52
- expiresAt: session.expiresAt,
53
- });
54
- state.redirect = `${this.oauth.frontendCallbackUrl}?${params}`;
55
- return;
56
- }
57
-
58
- return session;
59
- } catch {
60
- if (this.oauth.frontendCallbackUrl) {
61
- state.redirect = `${this.oauth.frontendCallbackUrl}?error=auth_failed`;
62
- return;
63
- }
64
- return 500;
65
- }
66
- },
67
-
68
- '/logout': ({ headers }) => {
69
- const sessionId = headers['session-id'];
70
- if (sessionId) this.oauth.logout(sessionId);
71
- },
72
- }
73
- };
74
- }
package/src/main.js DELETED
@@ -1,79 +0,0 @@
1
- import config from 'stonyx/config';
2
- import log from 'stonyx/log';
3
- import { waitForModule } from 'stonyx';
4
- import RestServer from '@stonyx/rest-server';
5
- import TokenManager from './token-manager.js';
6
- import SessionManager from './session-manager.js';
7
- import AuthRequest from './auth-request.js';
8
-
9
- export default class OAuth {
10
- providers = new Map();
11
- pendingStates = new Map();
12
-
13
- constructor() {
14
- if (OAuth.instance) return OAuth.instance;
15
- OAuth.instance = this;
16
- }
17
-
18
- async init() {
19
- const { providers, sessionDuration, frontendCallbackUrl } = config.oauth;
20
- this.frontendCallbackUrl = frontendCallbackUrl;
21
-
22
- for (const [name, providerConfig] of Object.entries(providers)) {
23
- const modulePath = providerConfig.module
24
- ? `${config.rootPath}/${providerConfig.module}`
25
- : `./providers/${name}.js`;
26
- const { default: Provider } = await import(modulePath);
27
- const flow = new Provider(providerConfig);
28
- this.providers.set(name, { flow, tokenManager: new TokenManager(flow) });
29
- }
30
-
31
- this.sessionManager = new SessionManager(sessionDuration);
32
-
33
- await waitForModule('rest-server');
34
- RestServer.instance.mountRoute(AuthRequest, { name: 'auth', options: this });
35
-
36
- log.oauth?.('OAuth module initialized');
37
- }
38
-
39
- getProvider(name) {
40
- const provider = this.providers.get(name);
41
- if (!provider) throw new Error(`OAuth provider "${name}" is not configured`);
42
- return provider;
43
- }
44
-
45
- getAuthorizationUrl(providerName) {
46
- const { flow } = this.getProvider(providerName);
47
- const stateToken = crypto.randomUUID();
48
- this.pendingStates.set(stateToken, Date.now());
49
- return flow.buildAuthorizationUrl(stateToken);
50
- }
51
-
52
- async handleCallback(providerName, code, stateToken) {
53
- if (!stateToken || !this.pendingStates.has(stateToken)) {
54
- throw new Error('Invalid or missing state token');
55
- }
56
-
57
- const stateCreatedAt = this.pendingStates.get(stateToken);
58
- this.pendingStates.delete(stateToken);
59
-
60
- const TEN_MINUTES = 10 * 60 * 1000;
61
- if (Date.now() - stateCreatedAt > TEN_MINUTES) {
62
- throw new Error('State token has expired');
63
- }
64
-
65
- const { flow, tokenManager } = this.getProvider(providerName);
66
- const tokens = await tokenManager.getTokens(code);
67
- const rawUser = await flow.fetchUserInfo(tokens.accessToken);
68
- const user = flow.normalizeUser(rawUser);
69
- return this.sessionManager.create(user, tokens);
70
- }
71
-
72
- getSession(sessionId) {
73
- return this.sessionManager.validate(sessionId);
74
- }
75
-
76
- logout(sessionId) {
77
- this.sessionManager.destroy(sessionId);
78
- }
79
- }
@@ -1,26 +0,0 @@
1
- export default class TokenManager {
2
- constructor(flow) {
3
- this.flow = flow;
4
- }
5
-
6
- async getTokens(code) {
7
- const tokens = await this.flow.exchangeCode(code);
8
- tokens.expiresAt = Date.now() + (tokens.expiresIn * 1000);
9
- return tokens;
10
- }
11
-
12
- async refresh(refreshToken) {
13
- const tokens = await this.flow.refreshAccessToken(refreshToken);
14
- tokens.expiresAt = Date.now() + (tokens.expiresIn * 1000);
15
- return tokens;
16
- }
17
-
18
- async revoke(accessToken) {
19
- return this.flow.revokeToken(accessToken);
20
- }
21
-
22
- isExpired(tokenData) {
23
- if (!tokenData?.expiresAt) return true;
24
- return Date.now() >= tokenData.expiresAt;
25
- }
26
- }
@@ -1,18 +0,0 @@
1
- export default {
2
- restServer: {
3
- dir: './test/sample/requests',
4
- },
5
- oauth: {
6
- providers: {
7
- mock: {
8
- clientId: 'test-client-id',
9
- clientSecret: 'test-client-secret',
10
- redirectUri: 'http://localhost:2666/auth/callback/mock',
11
- scopes: ['identify'],
12
- module: './test/sample/providers/mock.js',
13
- }
14
- },
15
- sessionDuration: 3600,
16
- frontendCallbackUrl: 'http://localhost:4200/auth/callback',
17
- }
18
- };