@aponiajs/session 0.0.0-stage → 1.0.0-beta.64
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/README.md +124 -2
- package/dist/index.d.mts +181 -0
- package/dist/index.mjs +411 -0
- package/llms.txt +25 -0
- package/package.json +58 -4
package/README.md
CHANGED
|
@@ -1,3 +1,125 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @aponiajs/session
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Signed session cookies and a bounded session store for AponiaJS.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
bun add @aponiajs/session@alpha
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Use it
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { Module } from "@aponiajs/common";
|
|
13
|
+
import { SessionModule } from "@aponiajs/session";
|
|
14
|
+
|
|
15
|
+
@Module({
|
|
16
|
+
imports: [
|
|
17
|
+
SessionModule.forRoot({
|
|
18
|
+
secret: process.env.SESSION_SECRET!,
|
|
19
|
+
}),
|
|
20
|
+
],
|
|
21
|
+
})
|
|
22
|
+
export class AppModule {}
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { Injectable } from "@aponiajs/common";
|
|
27
|
+
import { SessionService } from "@aponiajs/session";
|
|
28
|
+
|
|
29
|
+
@Injectable()
|
|
30
|
+
export class LoginService {
|
|
31
|
+
constructor(private readonly sessions: SessionService) {}
|
|
32
|
+
|
|
33
|
+
async login(userId: string) {
|
|
34
|
+
return this.sessions.start({ userId });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async logout() {
|
|
38
|
+
await this.sessions.destroy();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
The global middleware reads the signed cookie before the handler and writes or
|
|
44
|
+
removes it after the handler. `SessionService.current()` reads the session the
|
|
45
|
+
request loaded, and `@Session()` injects it as a handler parameter:
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import { Controller, Get } from "@aponiajs/common";
|
|
49
|
+
import { Session } from "@aponiajs/session";
|
|
50
|
+
|
|
51
|
+
@Controller("account")
|
|
52
|
+
export class AccountController {
|
|
53
|
+
@Get()
|
|
54
|
+
read(@Session("userId") userId: string | undefined) {
|
|
55
|
+
return { userId };
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`@Session()` answers the whole session; `@Session("userId")` answers one field
|
|
61
|
+
of its data. A request with no valid session answers `undefined`.
|
|
62
|
+
|
|
63
|
+
### Async registration
|
|
64
|
+
|
|
65
|
+
`forRootAsync` accepts the same options through `useFactory`, `useClass`, or
|
|
66
|
+
`useExisting`:
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
SessionModule.forRootAsync({
|
|
70
|
+
useFactory: () => ({
|
|
71
|
+
secret: process.env.SESSION_SECRET!,
|
|
72
|
+
}),
|
|
73
|
+
});
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
A factory may return a Promise. `useClass` constructs a class implementing
|
|
77
|
+
`create()`, and `useExisting` points at a provider that does.
|
|
78
|
+
|
|
79
|
+
## Options
|
|
80
|
+
|
|
81
|
+
| Option | Default | Meaning |
|
|
82
|
+
| ----------------- | ------------ | ------------------------------------ |
|
|
83
|
+
| `secret` | required | HMAC secret, at least 32 characters. |
|
|
84
|
+
| `cookieName` | `aponia.sid` | Session cookie name. |
|
|
85
|
+
| `ttlMs` | `86_400_000` | Absolute session lifetime. |
|
|
86
|
+
| `store` | memory | A custom `SessionStore`. |
|
|
87
|
+
| `maxSessions` | `10_000` | In-memory store cap. |
|
|
88
|
+
| `rolling` | `false` | Extend the lifetime on each read. |
|
|
89
|
+
| `cookie.secure` | `true` | The cookie `Secure` attribute. |
|
|
90
|
+
| `cookie.sameSite` | `lax` | The cookie `SameSite` attribute. |
|
|
91
|
+
|
|
92
|
+
## Behavior
|
|
93
|
+
|
|
94
|
+
- The cookie carries a signed session id, never the session data.
|
|
95
|
+
- The cookie is `HttpOnly`; the application reads the session through
|
|
96
|
+
`SessionService`, not JavaScript.
|
|
97
|
+
- `start` creates a session and marks the cookie for the response.
|
|
98
|
+
- `regenerate` replaces the session with a new id and lifetime; use it after login, a role change, or a password reset so a fixation id stops being accepted.
|
|
99
|
+
- `update` replaces the data; `rolling` also extends the lifetime.
|
|
100
|
+
- `destroy` deletes the session and removes the cookie.
|
|
101
|
+
- A tampered or expired cookie is ignored and cleared.
|
|
102
|
+
- The memory store is bounded and evicts the oldest insertion.
|
|
103
|
+
- Configuration failures are `INVALID_SESSION_OPTIONS` with a frozen issue list.
|
|
104
|
+
|
|
105
|
+
## Limits
|
|
106
|
+
|
|
107
|
+
The default store is process-local and not a distributed session store. A
|
|
108
|
+
multi-process deployment supplies a shared `SessionStore` and keeps the same
|
|
109
|
+
signed-cookie contract.
|
|
110
|
+
|
|
111
|
+
## Bootstrap
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
import { AponiaFactory } from "@aponiajs/platform-elysia";
|
|
115
|
+
import { AppModule } from "./app.module.ts";
|
|
116
|
+
|
|
117
|
+
const application = await AponiaFactory.create(AppModule);
|
|
118
|
+
await application.listen(Number(Bun.env.PORT ?? 3000));
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Documentation
|
|
122
|
+
|
|
123
|
+
- [Published packages](../../docs/reference/packages.md)
|
|
124
|
+
- [AponiaJS architecture](../../docs/build/architecture-and-style.md)
|
|
125
|
+
- [npm](https://www.npmjs.com/package/@aponiajs/session)
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { DynamicModule, MiddlewareConsumer, ModuleAsyncOptions } from "@aponiajs/common";
|
|
3
|
+
/** Session data, keyed by the application. */
|
|
4
|
+
interface Session$1<TData extends Record<string, unknown> = Record<string, unknown>> {
|
|
5
|
+
readonly id: string;
|
|
6
|
+
readonly data: TData;
|
|
7
|
+
readonly createdAt: number;
|
|
8
|
+
readonly expiresAt: number;
|
|
9
|
+
}
|
|
10
|
+
/** The storage contract a session registration accepts. */
|
|
11
|
+
interface SessionStore {
|
|
12
|
+
get(id: string): Session$1 | undefined | Promise<Session$1 | undefined>;
|
|
13
|
+
set(session: Session$1): void | Promise<void>;
|
|
14
|
+
delete(id: string): boolean | Promise<boolean>;
|
|
15
|
+
clear(): void | Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
/** Cookie attributes a session registration accepts. */
|
|
18
|
+
interface SessionCookieOptions {
|
|
19
|
+
readonly secure?: boolean;
|
|
20
|
+
readonly sameSite?: "lax" | "strict" | "none";
|
|
21
|
+
readonly path?: string;
|
|
22
|
+
readonly domain?: string;
|
|
23
|
+
}
|
|
24
|
+
/** Options a session registration accepts. */
|
|
25
|
+
interface SessionModuleOptions {
|
|
26
|
+
/** The HMAC secret; at least 32 characters. */
|
|
27
|
+
readonly secret: string;
|
|
28
|
+
/** The cookie name; defaults to `aponia.sid`. */
|
|
29
|
+
readonly cookieName?: string;
|
|
30
|
+
/** The absolute lifetime in milliseconds; defaults to 24 hours. */
|
|
31
|
+
readonly ttlMs?: number;
|
|
32
|
+
/** The store to use; defaults to a bounded in-memory store. */
|
|
33
|
+
readonly store?: SessionStore;
|
|
34
|
+
/** The in-memory store's cap; ignored when `store` is supplied. */
|
|
35
|
+
readonly maxSessions?: number;
|
|
36
|
+
/** Cookie attributes. */
|
|
37
|
+
readonly cookie?: SessionCookieOptions;
|
|
38
|
+
/** Whether a session's lifetime is extended on each read; defaults to false. */
|
|
39
|
+
readonly rolling?: boolean;
|
|
40
|
+
/** The plugin module identity; defaults to `session`. */
|
|
41
|
+
readonly key?: string;
|
|
42
|
+
}
|
|
43
|
+
/** The validated options the service and plugin read. */
|
|
44
|
+
interface ResolvedSessionOptions {
|
|
45
|
+
readonly secret: string;
|
|
46
|
+
readonly cookieName: string;
|
|
47
|
+
readonly ttlMs: number;
|
|
48
|
+
readonly maxSessions: number;
|
|
49
|
+
readonly cookie: Readonly<{
|
|
50
|
+
readonly secure: boolean;
|
|
51
|
+
readonly sameSite: "lax" | "strict" | "none";
|
|
52
|
+
readonly path: string;
|
|
53
|
+
readonly domain: string | undefined;
|
|
54
|
+
}>;
|
|
55
|
+
readonly rolling: boolean;
|
|
56
|
+
}
|
|
57
|
+
/** The registration options a factory supplies. */
|
|
58
|
+
type SessionModuleAsyncOptions = ModuleAsyncOptions<SessionModuleOptions> & {
|
|
59
|
+
/** Names the module identity; defaults to `session`. */
|
|
60
|
+
readonly key?: string;
|
|
61
|
+
};
|
|
62
|
+
/** Provides the session service and mounts the cookie middleware. */
|
|
63
|
+
export declare class SessionModule {
|
|
64
|
+
/**
|
|
65
|
+
* Mounts the session middleware ahead of every route.
|
|
66
|
+
*
|
|
67
|
+
* The middleware is a provider the registration exports, so a module's own
|
|
68
|
+
* `configure` can name it and the container resolves the store, storage, and
|
|
69
|
+
* options it runs with.
|
|
70
|
+
*/
|
|
71
|
+
configure(consumer: MiddlewareConsumer): void;
|
|
72
|
+
/**
|
|
73
|
+
* Builds a session registration.
|
|
74
|
+
*
|
|
75
|
+
* @param options - Secret, cookie, TTL, store, and rolling policy.
|
|
76
|
+
* @returns The module registration an application imports.
|
|
77
|
+
* @throws An `AponiaError` with `INVALID_SESSION_OPTIONS` when an option is invalid.
|
|
78
|
+
*/
|
|
79
|
+
static forRoot(options: SessionModuleOptions): DynamicModule;
|
|
80
|
+
/**
|
|
81
|
+
* Builds a session registration whose options a factory resolves.
|
|
82
|
+
*
|
|
83
|
+
* `key` is read from the registration, not from the factory result, because
|
|
84
|
+
* it names the module identity before the container runs.
|
|
85
|
+
*
|
|
86
|
+
* @param options - The imports, injected tokens, factory, key, and extra providers.
|
|
87
|
+
* @returns The module registration an application imports.
|
|
88
|
+
*/
|
|
89
|
+
static forRootAsync(options: ModuleAsyncOptions<SessionModuleOptions> & {
|
|
90
|
+
readonly key?: string;
|
|
91
|
+
}): DynamicModule;
|
|
92
|
+
/**
|
|
93
|
+
* Builds a session registration.
|
|
94
|
+
*
|
|
95
|
+
* @deprecated Use {@link SessionModule.forRoot}; retained for the beta line.
|
|
96
|
+
*/
|
|
97
|
+
static register(options: SessionModuleOptions): DynamicModule;
|
|
98
|
+
}
|
|
99
|
+
/** The mutable state one request carries between the plugin and the service. */
|
|
100
|
+
interface SessionRequestState {
|
|
101
|
+
session: Session$1 | undefined;
|
|
102
|
+
started: boolean;
|
|
103
|
+
touched: boolean;
|
|
104
|
+
destroyed: boolean;
|
|
105
|
+
/**
|
|
106
|
+
* Writes the response cookie for one session.
|
|
107
|
+
*
|
|
108
|
+
* The plugin installs it before the request reaches the handler, and the
|
|
109
|
+
* service calls it the moment the session changes. Writing at the change
|
|
110
|
+
* rather than after `next()` keeps the cookie correct on a platform whose
|
|
111
|
+
* middleware chain does not wrap the handler.
|
|
112
|
+
*/
|
|
113
|
+
writeCookie?: ((session: Session$1) => void) | undefined;
|
|
114
|
+
/** Clears the response cookie. */
|
|
115
|
+
clearCookie?: (() => void) | undefined;
|
|
116
|
+
}
|
|
117
|
+
/** The session operations a handler calls. */
|
|
118
|
+
export declare class SessionService {
|
|
119
|
+
#private;
|
|
120
|
+
/** @internal Construct through `SessionModule.register`. */
|
|
121
|
+
constructor(storage: AsyncLocalStorage<SessionRequestState>, store: SessionStore, options: ResolvedSessionOptions);
|
|
122
|
+
/** The session loaded for the current request, if one is valid. */
|
|
123
|
+
current(): Session$1 | undefined;
|
|
124
|
+
/** Starts a new session and marks its cookie for the response. */
|
|
125
|
+
start<TData extends Record<string, unknown> = Record<string, unknown>>(data?: TData): Promise<Session$1<TData>>;
|
|
126
|
+
/**
|
|
127
|
+
* Replaces the current session with a new id and a new lifetime.
|
|
128
|
+
*
|
|
129
|
+
* Call it when a session's privilege changes — after login, a role change, or
|
|
130
|
+
* a password reset — so an id an attacker obtained before that point stops
|
|
131
|
+
* being accepted. The old entry is deleted, the new id is written, and the
|
|
132
|
+
* response carries the new cookie just as `start` does.
|
|
133
|
+
*/
|
|
134
|
+
regenerate<TData extends Record<string, unknown> = Record<string, unknown>>(data?: TData): Promise<Session$1<TData>>;
|
|
135
|
+
/** Replaces the current session's data. */
|
|
136
|
+
update<TData extends Record<string, unknown>>(data: TData): Promise<Session$1<TData> | undefined>;
|
|
137
|
+
/** Destroys the current session and removes its cookie. */
|
|
138
|
+
destroy(): Promise<boolean>;
|
|
139
|
+
/** Reads a session by id, outside the current request. */
|
|
140
|
+
get(id: string): Session$1 | undefined | Promise<Session$1 | undefined>;
|
|
141
|
+
/** Removes every session in the store. */
|
|
142
|
+
clear(): Promise<void>;
|
|
143
|
+
}
|
|
144
|
+
/** The session record the plugin loaded for the current request. */
|
|
145
|
+
export type Session = Session$1;
|
|
146
|
+
/**
|
|
147
|
+
* Injects the current session, or one field of its data.
|
|
148
|
+
*
|
|
149
|
+
* `@Session()` answers the whole `Session`; `@Session("user")` answers
|
|
150
|
+
* `session.data.user`. A request with no valid session answers `undefined`.
|
|
151
|
+
* A started session is written by `SessionService.start` during the handler,
|
|
152
|
+
* so this decorator reads the session the plugin loaded before it.
|
|
153
|
+
*
|
|
154
|
+
* @param property - A key of the session's data, or the whole session.
|
|
155
|
+
* @returns A parameter decorator recording the binding.
|
|
156
|
+
*
|
|
157
|
+
* @example
|
|
158
|
+
* ```ts
|
|
159
|
+
* current(@Session("user") user: string | undefined) {}
|
|
160
|
+
* ```
|
|
161
|
+
*/
|
|
162
|
+
export declare const Session: (dataOrPipe?: unknown, ...pipes: readonly import("@aponiajs/common").PipeType[]) => ParameterDecorator;
|
|
163
|
+
/** Options for the bounded in-memory session store. */
|
|
164
|
+
interface MemorySessionStoreOptions {
|
|
165
|
+
/** The maximum number of sessions; the oldest insertion is evicted first. */
|
|
166
|
+
readonly maxSessions?: number;
|
|
167
|
+
/** A clock, so tests can advance time without sleeping. Defaults to `Date.now`. */
|
|
168
|
+
readonly now?: () => number;
|
|
169
|
+
}
|
|
170
|
+
/** A bounded, process-local session store with lazy expiry. */
|
|
171
|
+
export declare class MemorySessionStore implements SessionStore {
|
|
172
|
+
#private;
|
|
173
|
+
constructor(options?: MemorySessionStoreOptions);
|
|
174
|
+
get(id: string): Session$1 | undefined;
|
|
175
|
+
set(session: Session$1): void;
|
|
176
|
+
delete(id: string): boolean;
|
|
177
|
+
clear(): void;
|
|
178
|
+
/** The number of sessions retained, including expired ones. */
|
|
179
|
+
get size(): number;
|
|
180
|
+
}
|
|
181
|
+
export type { MemorySessionStoreOptions, SessionCookieOptions, SessionModuleAsyncOptions, SessionModuleOptions, SessionStore };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { AponiaError, Module, clearCookie, createParamDecorator, createToken, moduleOptionsProviders, provideClass, provideFactory, provideValue, readCookies, registerAsyncContextExit, writeCookie } from "@aponiajs/common";
|
|
3
|
+
import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
4
|
+
// src/policy/session-token.ts
|
|
5
|
+
/** Signs a session id into the cookie value. */
|
|
6
|
+
function issueSessionToken(id, secret) {
|
|
7
|
+
return `${id}.${sign(id, secret)}`;
|
|
8
|
+
}
|
|
9
|
+
/** Verifies a cookie value and answers its session id. */
|
|
10
|
+
function readSessionId(token, secret) {
|
|
11
|
+
const [id, signature, ...rest] = token.split(".");
|
|
12
|
+
if (id === void 0 || signature === void 0 || rest.length > 0) return;
|
|
13
|
+
const expected = sign(id, secret);
|
|
14
|
+
const actualBytes = Buffer.from(signature);
|
|
15
|
+
const expectedBytes = Buffer.from(expected);
|
|
16
|
+
return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes) ? id : void 0;
|
|
17
|
+
}
|
|
18
|
+
function sign(id, secret) {
|
|
19
|
+
return createHmac("sha256", secret).update(id).digest("hex");
|
|
20
|
+
}
|
|
21
|
+
// src/service/session-parameter.ts
|
|
22
|
+
/**
|
|
23
|
+
* Per-request state, keyed by the request object.
|
|
24
|
+
*
|
|
25
|
+
* It deliberately never touches the platform `store`: that store is shared by
|
|
26
|
+
* every request on the application, so a concurrent request would overwrite the
|
|
27
|
+
* state a handler is about to read.
|
|
28
|
+
*/
|
|
29
|
+
const requestStates = /* @__PURE__ */ new WeakMap();
|
|
30
|
+
/**
|
|
31
|
+
* Records the state the session middleware loaded for one request.
|
|
32
|
+
*
|
|
33
|
+
* @internal
|
|
34
|
+
* @param request - The request the middleware is running for.
|
|
35
|
+
* @param state - The state the parameter decorator answers from.
|
|
36
|
+
*/
|
|
37
|
+
function setSessionRequestState(request, state) {
|
|
38
|
+
requestStates.set(request, state);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Injects the current session, or one field of its data.
|
|
42
|
+
*
|
|
43
|
+
* `@Session()` answers the whole `Session`; `@Session("user")` answers
|
|
44
|
+
* `session.data.user`. A request with no valid session answers `undefined`.
|
|
45
|
+
* A started session is written by `SessionService.start` during the handler,
|
|
46
|
+
* so this decorator reads the session the plugin loaded before it.
|
|
47
|
+
*
|
|
48
|
+
* @param property - A key of the session's data, or the whole session.
|
|
49
|
+
* @returns A parameter decorator recording the binding.
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```ts
|
|
53
|
+
* current(@Session("user") user: string | undefined) {}
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
const Session = createParamDecorator((property, context) => {
|
|
57
|
+
const session = requestStates.get(context.request)?.session;
|
|
58
|
+
if (session === void 0) return;
|
|
59
|
+
if (property === void 0) return session;
|
|
60
|
+
return typeof property === "string" ? session.data[property] : void 0;
|
|
61
|
+
});
|
|
62
|
+
// src/middleware/session.middleware.ts
|
|
63
|
+
/**
|
|
64
|
+
* Loads the session a request's cookie names, and writes the cookie the handler
|
|
65
|
+
* changed.
|
|
66
|
+
*
|
|
67
|
+
* It runs before the route's guards and after it, which is exactly the window a
|
|
68
|
+
* session needs: the state is entered before anything can read it, and the
|
|
69
|
+
* cookie is written once the handler has had its say. The middleware is
|
|
70
|
+
* runtime-neutral — the cookie is read from the request context and written
|
|
71
|
+
* into the response settings — so one implementation serves every platform.
|
|
72
|
+
*/
|
|
73
|
+
var SessionMiddleware = class {
|
|
74
|
+
#storage;
|
|
75
|
+
#store;
|
|
76
|
+
#options;
|
|
77
|
+
constructor(storage, store, options) {
|
|
78
|
+
this.#storage = storage;
|
|
79
|
+
this.#store = store;
|
|
80
|
+
this.#options = options;
|
|
81
|
+
}
|
|
82
|
+
async use(context, next) {
|
|
83
|
+
const state = {
|
|
84
|
+
session: void 0,
|
|
85
|
+
started: false,
|
|
86
|
+
touched: false,
|
|
87
|
+
destroyed: false,
|
|
88
|
+
writeCookie: (session) => {
|
|
89
|
+
this.#writeCookie(context, session);
|
|
90
|
+
},
|
|
91
|
+
clearCookie: () => {
|
|
92
|
+
this.#clearCookie(context);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
this.#storage.enterWith(state);
|
|
96
|
+
setSessionRequestState(context.request, state);
|
|
97
|
+
await this.#load(context, state);
|
|
98
|
+
return await next();
|
|
99
|
+
}
|
|
100
|
+
async #load(context, state) {
|
|
101
|
+
const token = readCookies(context.request)[this.#options.cookieName]?.value;
|
|
102
|
+
if (typeof token !== "string") return;
|
|
103
|
+
const id = readSessionId(token, this.#options.secret);
|
|
104
|
+
if (id === void 0) {
|
|
105
|
+
state.destroyed = true;
|
|
106
|
+
state.clearCookie?.();
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
const session = await this.#store.get(id);
|
|
110
|
+
if (session === void 0 || session.expiresAt <= Date.now()) {
|
|
111
|
+
state.destroyed = true;
|
|
112
|
+
state.clearCookie?.();
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
state.session = session;
|
|
116
|
+
if (this.#options.rolling) {
|
|
117
|
+
const extended = Object.freeze({
|
|
118
|
+
...session,
|
|
119
|
+
expiresAt: Date.now() + this.#options.ttlMs
|
|
120
|
+
});
|
|
121
|
+
await this.#store.set(extended);
|
|
122
|
+
state.session = extended;
|
|
123
|
+
state.touched = true;
|
|
124
|
+
state.writeCookie?.(extended);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
#writeCookie(context, session) {
|
|
128
|
+
const attributes = this.#options.cookie;
|
|
129
|
+
writeCookie(context.set, this.#options.cookieName, issueSessionToken(session.id, this.#options.secret), {
|
|
130
|
+
httpOnly: true,
|
|
131
|
+
secure: attributes.secure,
|
|
132
|
+
sameSite: attributes.sameSite,
|
|
133
|
+
path: attributes.path,
|
|
134
|
+
maxAge: Math.max(1, Math.ceil((session.expiresAt - Date.now()) / 1e3)),
|
|
135
|
+
...attributes.domain === void 0 ? {} : { domain: attributes.domain }
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
#clearCookie(context) {
|
|
139
|
+
const attributes = this.#options.cookie;
|
|
140
|
+
clearCookie(context.set, this.#options.cookieName, {
|
|
141
|
+
path: attributes.path,
|
|
142
|
+
...attributes.domain === void 0 ? {} : { domain: attributes.domain }
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
// src/service/session.service.ts
|
|
147
|
+
/** The session operations a handler calls. */
|
|
148
|
+
var SessionService = class {
|
|
149
|
+
#storage;
|
|
150
|
+
#store;
|
|
151
|
+
#options;
|
|
152
|
+
/** @internal Construct through `SessionModule.register`. */
|
|
153
|
+
constructor(storage, store, options) {
|
|
154
|
+
this.#storage = storage;
|
|
155
|
+
registerAsyncContextExit((work) => this.#storage.exit(work));
|
|
156
|
+
this.#store = store;
|
|
157
|
+
this.#options = options;
|
|
158
|
+
}
|
|
159
|
+
/** The session loaded for the current request, if one is valid. */
|
|
160
|
+
current() {
|
|
161
|
+
return this.#storage.getStore()?.session;
|
|
162
|
+
}
|
|
163
|
+
/** Starts a new session and marks its cookie for the response. */
|
|
164
|
+
async start(data = {}) {
|
|
165
|
+
const state = this.#state();
|
|
166
|
+
const now = Date.now();
|
|
167
|
+
const session = Object.freeze({
|
|
168
|
+
id: randomUUID(),
|
|
169
|
+
data: Object.freeze({ ...data }),
|
|
170
|
+
createdAt: now,
|
|
171
|
+
expiresAt: now + this.#options.ttlMs
|
|
172
|
+
});
|
|
173
|
+
await this.#store.set(session);
|
|
174
|
+
state.session = session;
|
|
175
|
+
state.started = true;
|
|
176
|
+
state.destroyed = false;
|
|
177
|
+
state.writeCookie?.(session);
|
|
178
|
+
return session;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Replaces the current session with a new id and a new lifetime.
|
|
182
|
+
*
|
|
183
|
+
* Call it when a session's privilege changes — after login, a role change, or
|
|
184
|
+
* a password reset — so an id an attacker obtained before that point stops
|
|
185
|
+
* being accepted. The old entry is deleted, the new id is written, and the
|
|
186
|
+
* response carries the new cookie just as `start` does.
|
|
187
|
+
*/
|
|
188
|
+
async regenerate(data = {}) {
|
|
189
|
+
const state = this.#state();
|
|
190
|
+
const current = state.session;
|
|
191
|
+
if (current !== void 0) await this.#store.delete(current.id);
|
|
192
|
+
const now = Date.now();
|
|
193
|
+
const session = Object.freeze({
|
|
194
|
+
id: randomUUID(),
|
|
195
|
+
data: Object.freeze({ ...data }),
|
|
196
|
+
createdAt: now,
|
|
197
|
+
expiresAt: now + this.#options.ttlMs
|
|
198
|
+
});
|
|
199
|
+
await this.#store.set(session);
|
|
200
|
+
state.session = session;
|
|
201
|
+
state.started = true;
|
|
202
|
+
state.touched = false;
|
|
203
|
+
state.destroyed = false;
|
|
204
|
+
state.writeCookie?.(session);
|
|
205
|
+
return session;
|
|
206
|
+
}
|
|
207
|
+
/** Replaces the current session's data. */
|
|
208
|
+
async update(data) {
|
|
209
|
+
const state = this.#state();
|
|
210
|
+
const current = state.session;
|
|
211
|
+
if (current === void 0) return;
|
|
212
|
+
const now = Date.now();
|
|
213
|
+
const session = Object.freeze({
|
|
214
|
+
id: current.id,
|
|
215
|
+
data: Object.freeze({ ...data }),
|
|
216
|
+
createdAt: current.createdAt,
|
|
217
|
+
expiresAt: this.#options.rolling ? now + this.#options.ttlMs : current.expiresAt
|
|
218
|
+
});
|
|
219
|
+
await this.#store.set(session);
|
|
220
|
+
state.session = session;
|
|
221
|
+
state.touched = this.#options.rolling;
|
|
222
|
+
if (state.touched) state.writeCookie?.(session);
|
|
223
|
+
return session;
|
|
224
|
+
}
|
|
225
|
+
/** Destroys the current session and removes its cookie. */
|
|
226
|
+
async destroy() {
|
|
227
|
+
const state = this.#state();
|
|
228
|
+
const current = state.session;
|
|
229
|
+
if (current === void 0) {
|
|
230
|
+
state.destroyed = true;
|
|
231
|
+
return false;
|
|
232
|
+
}
|
|
233
|
+
const deleted = await this.#store.delete(current.id);
|
|
234
|
+
state.session = void 0;
|
|
235
|
+
state.destroyed = true;
|
|
236
|
+
state.clearCookie?.();
|
|
237
|
+
return deleted;
|
|
238
|
+
}
|
|
239
|
+
/** Reads a session by id, outside the current request. */
|
|
240
|
+
get(id) {
|
|
241
|
+
return this.#store.get(id);
|
|
242
|
+
}
|
|
243
|
+
/** Removes every session in the store. */
|
|
244
|
+
async clear() {
|
|
245
|
+
await this.#store.clear();
|
|
246
|
+
}
|
|
247
|
+
#state() {
|
|
248
|
+
const state = this.#storage.getStore();
|
|
249
|
+
if (state === void 0) throw new AponiaError("MISSING_REQUEST_CONTEXT", "SessionService must be used inside a session-enabled request.", { service: "SessionService" });
|
|
250
|
+
return state;
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
// src/store/memory-session.store.ts
|
|
254
|
+
const defaultMaxSessions$1 = 1e4;
|
|
255
|
+
/** A bounded, process-local session store with lazy expiry. */
|
|
256
|
+
var MemorySessionStore = class {
|
|
257
|
+
#sessions = /* @__PURE__ */ new Map();
|
|
258
|
+
#maxSessions;
|
|
259
|
+
#now;
|
|
260
|
+
constructor(options = {}) {
|
|
261
|
+
const maxSessions = options.maxSessions ?? defaultMaxSessions$1;
|
|
262
|
+
if (!Number.isInteger(maxSessions) || maxSessions < 1) throw new AponiaError("INVALID_SESSION_OPTIONS", `MemorySessionStore maxSessions must be a positive integer, received ${String(maxSessions)}.`, { issues: Object.freeze(["maxSessions must be a positive integer"]) });
|
|
263
|
+
this.#maxSessions = maxSessions;
|
|
264
|
+
this.#now = options.now ?? Date.now;
|
|
265
|
+
}
|
|
266
|
+
get(id) {
|
|
267
|
+
const session = this.#sessions.get(id);
|
|
268
|
+
if (session === void 0) return;
|
|
269
|
+
if (session.expiresAt <= this.#now()) {
|
|
270
|
+
this.#sessions.delete(id);
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
return session;
|
|
274
|
+
}
|
|
275
|
+
set(session) {
|
|
276
|
+
if (!this.#sessions.has(session.id) && this.#sessions.size >= this.#maxSessions) {
|
|
277
|
+
const oldest = this.#sessions.keys().next().value;
|
|
278
|
+
if (oldest !== void 0) this.#sessions.delete(oldest);
|
|
279
|
+
}
|
|
280
|
+
this.#sessions.set(session.id, session);
|
|
281
|
+
}
|
|
282
|
+
delete(id) {
|
|
283
|
+
return this.#sessions.delete(id);
|
|
284
|
+
}
|
|
285
|
+
clear() {
|
|
286
|
+
this.#sessions.clear();
|
|
287
|
+
}
|
|
288
|
+
/** The number of sessions retained, including expired ones. */
|
|
289
|
+
get size() {
|
|
290
|
+
return this.#sessions.size;
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
// \0@oxc-project+runtime@0.156.0/helpers/esm/decorate.js
|
|
294
|
+
function __decorate(decorators, target, key, desc) {
|
|
295
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
296
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
297
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
298
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
299
|
+
}
|
|
300
|
+
// src/module/session.module.ts
|
|
301
|
+
var _SessionModule;
|
|
302
|
+
const defaultTtlMs = 864e5;
|
|
303
|
+
const defaultMaxSessions = 1e4;
|
|
304
|
+
const SESSION_STORAGE = createToken("aponia.session.storage");
|
|
305
|
+
const SESSION_STORE = createToken("aponia.session.store");
|
|
306
|
+
const SESSION_OPTIONS = createToken("aponia.session.options");
|
|
307
|
+
let SessionModule = _SessionModule = class SessionModule {
|
|
308
|
+
/**
|
|
309
|
+
* Mounts the session middleware ahead of every route.
|
|
310
|
+
*
|
|
311
|
+
* The middleware is a provider the registration exports, so a module's own
|
|
312
|
+
* `configure` can name it and the container resolves the store, storage, and
|
|
313
|
+
* options it runs with.
|
|
314
|
+
*/
|
|
315
|
+
configure(consumer) {
|
|
316
|
+
consumer.apply(SessionMiddleware).forRoutes("/*");
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Builds a session registration.
|
|
320
|
+
*
|
|
321
|
+
* @param options - Secret, cookie, TTL, store, and rolling policy.
|
|
322
|
+
* @returns The module registration an application imports.
|
|
323
|
+
* @throws An `AponiaError` with `INVALID_SESSION_OPTIONS` when an option is invalid.
|
|
324
|
+
*/
|
|
325
|
+
static forRoot(options) {
|
|
326
|
+
return registration([provideValue(SESSION_OPTIONS, resolveOptions(options))], options.key);
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Builds a session registration whose options a factory resolves.
|
|
330
|
+
*
|
|
331
|
+
* `key` is read from the registration, not from the factory result, because
|
|
332
|
+
* it names the module identity before the container runs.
|
|
333
|
+
*
|
|
334
|
+
* @param options - The imports, injected tokens, factory, key, and extra providers.
|
|
335
|
+
* @returns The module registration an application imports.
|
|
336
|
+
*/
|
|
337
|
+
static forRootAsync(options) {
|
|
338
|
+
return registration(moduleOptionsProviders(SESSION_OPTIONS, options, resolveOptions), options.key, options.imports, options.extraProviders);
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Builds a session registration.
|
|
342
|
+
*
|
|
343
|
+
* @deprecated Use {@link SessionModule.forRoot}; retained for the beta line.
|
|
344
|
+
*/
|
|
345
|
+
static register(options) {
|
|
346
|
+
return _SessionModule.forRoot(options);
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
SessionModule = _SessionModule = __decorate([Module({})], SessionModule);
|
|
350
|
+
function registration(optionsProviders, key, imports = [], extraProviders = []) {
|
|
351
|
+
const moduleKey = key ?? "session";
|
|
352
|
+
return Object.freeze({
|
|
353
|
+
module: SessionModule,
|
|
354
|
+
id: `SessionModule[${moduleKey}]`,
|
|
355
|
+
instanceId: Symbol.for(`aponia.session:${moduleKey}`),
|
|
356
|
+
imports: Object.freeze([...imports]),
|
|
357
|
+
providers: Object.freeze([
|
|
358
|
+
provideValue(SESSION_STORAGE, new AsyncLocalStorage()),
|
|
359
|
+
...optionsProviders,
|
|
360
|
+
provideFactory(SESSION_STORE, [SESSION_OPTIONS], (options) => options.store ?? new MemorySessionStore({ maxSessions: options.maxSessions })),
|
|
361
|
+
provideClass(SessionMiddleware, [
|
|
362
|
+
SESSION_STORAGE,
|
|
363
|
+
SESSION_STORE,
|
|
364
|
+
SESSION_OPTIONS
|
|
365
|
+
]),
|
|
366
|
+
provideFactory(SessionService, [
|
|
367
|
+
SESSION_STORAGE,
|
|
368
|
+
SESSION_STORE,
|
|
369
|
+
SESSION_OPTIONS
|
|
370
|
+
], (storage, store, options) => new SessionService(storage, store, options)),
|
|
371
|
+
...extraProviders
|
|
372
|
+
]),
|
|
373
|
+
exports: Object.freeze([SessionService, SessionMiddleware])
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
function resolveOptions(options) {
|
|
377
|
+
const cookieName = options.cookieName ?? "aponia.sid";
|
|
378
|
+
const ttlMs = options.ttlMs ?? defaultTtlMs;
|
|
379
|
+
const maxSessions = options.maxSessions ?? defaultMaxSessions;
|
|
380
|
+
const cookie = options.cookie ?? {};
|
|
381
|
+
const issues = [];
|
|
382
|
+
if (typeof options.secret !== "string" || options.secret.length < 32) issues.push("secret must be a string of at least 32 characters");
|
|
383
|
+
if (cookieName.trim() === "") issues.push("cookieName must be a non-empty string");
|
|
384
|
+
if (!Number.isInteger(ttlMs) || ttlMs < 1) issues.push("ttlMs must be a positive integer");
|
|
385
|
+
if (!Number.isInteger(maxSessions) || maxSessions < 1) issues.push("maxSessions must be a positive integer");
|
|
386
|
+
if (cookie.secure !== void 0 && typeof cookie.secure !== "boolean") issues.push("cookie.secure must be a boolean");
|
|
387
|
+
if (cookie.sameSite !== void 0 && ![
|
|
388
|
+
"lax",
|
|
389
|
+
"strict",
|
|
390
|
+
"none"
|
|
391
|
+
].includes(cookie.sameSite)) issues.push("cookie.sameSite must be \"lax\", \"strict\", or \"none\"");
|
|
392
|
+
if (cookie.path !== void 0 && cookie.path.trim() === "") issues.push("cookie.path must be a non-empty string");
|
|
393
|
+
if (cookie.domain !== void 0 && cookie.domain.trim() === "") issues.push("cookie.domain must be a non-empty string");
|
|
394
|
+
if (options.rolling !== void 0 && typeof options.rolling !== "boolean") issues.push("rolling must be a boolean");
|
|
395
|
+
if (issues.length > 0) throw new AponiaError("INVALID_SESSION_OPTIONS", `The session registration is invalid: ${issues.join("; ")}.`, { issues: Object.freeze(issues) });
|
|
396
|
+
return Object.freeze({
|
|
397
|
+
secret: options.secret,
|
|
398
|
+
cookieName,
|
|
399
|
+
ttlMs,
|
|
400
|
+
maxSessions,
|
|
401
|
+
cookie: Object.freeze({
|
|
402
|
+
secure: cookie.secure ?? true,
|
|
403
|
+
sameSite: cookie.sameSite ?? "lax",
|
|
404
|
+
path: cookie.path ?? "/",
|
|
405
|
+
domain: cookie.domain
|
|
406
|
+
}),
|
|
407
|
+
rolling: options.rolling ?? false,
|
|
408
|
+
store: options.store
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
export { MemorySessionStore, Session, SessionModule, SessionService };
|
package/llms.txt
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# @aponiajs/session
|
|
2
|
+
|
|
3
|
+
> Signed session cookies and a bounded session store for an AponiaJS application, with `SessionService` start, regenerate, update, read, and destroy operations.
|
|
4
|
+
|
|
5
|
+
## What this package exports
|
|
6
|
+
|
|
7
|
+
- `SessionModule.forRoot({ secret, cookieName?, ttlMs?, store?, maxSessions?, cookie?, rolling?, key? })`: the module registration an application imports; `register` is the deprecated beta alias.
|
|
8
|
+
- `SessionService`: `current`, `start`, `regenerate`, `update`, `destroy`, `get`, and `clear`.
|
|
9
|
+
- `MemorySessionStore`: a bounded process-local store with lazy expiry and oldest-insertion eviction.
|
|
10
|
+
- `Session`, `SessionStore`, `SessionCookieOptions`, `SessionModuleOptions`: the public contracts.
|
|
11
|
+
|
|
12
|
+
## Behavior a consumer can rely on
|
|
13
|
+
|
|
14
|
+
- The cookie carries a signed session id, never session data.
|
|
15
|
+
- The cookie is `HttpOnly`; the application reads the session through the service.
|
|
16
|
+
- `start` creates a session, `regenerate` replaces its id (deleting the old entry), `update` replaces data, and `destroy` removes the cookie.
|
|
17
|
+
- A tampered or expired cookie is ignored and cleared.
|
|
18
|
+
- The memory store is bounded and evicts the oldest insertion.
|
|
19
|
+
- An invalid option fails the boot with `INVALID_SESSION_OPTIONS` and a frozen issue list.
|
|
20
|
+
|
|
21
|
+
## Documentation
|
|
22
|
+
|
|
23
|
+
- [Package README](./README.md)
|
|
24
|
+
- [Published packages](../../docs/reference/packages.md)
|
|
25
|
+
- [npm](https://www.npmjs.com/package/@aponiajs/session)
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aponiajs/session",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0-beta.64",
|
|
4
|
+
"description": "Signed session cookies and a bounded session store for an Aponia application.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"aponia",
|
|
7
|
+
"aponiajs",
|
|
8
|
+
"bun",
|
|
9
|
+
"cookie",
|
|
10
|
+
"elysia",
|
|
11
|
+
"security",
|
|
12
|
+
"session",
|
|
13
|
+
"typescript"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://github.com/aponiajs/aponiajs#readme",
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/aponiajs/aponiajs/issues"
|
|
18
|
+
},
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"author": "AponiaJS contributors",
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://github.com/aponiajs/aponiajs.git",
|
|
24
|
+
"directory": "packages/session"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"dist",
|
|
28
|
+
"llms.txt"
|
|
29
|
+
],
|
|
30
|
+
"type": "module",
|
|
31
|
+
"exports": {
|
|
32
|
+
".": "./dist/index.mjs",
|
|
33
|
+
"./package.json": "./package.json"
|
|
34
|
+
},
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "bunx --bun vp pack",
|
|
40
|
+
"dev": "bunx --bun vp pack --watch",
|
|
41
|
+
"test": "bun test",
|
|
42
|
+
"test:vite-plus": "vp test",
|
|
43
|
+
"check": "bunx --bun vp check",
|
|
44
|
+
"prepublishOnly": "bun run build"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"@aponiajs/common": "1.0.0-beta.64"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@aponiajs/core": "1.0.0-beta.64",
|
|
51
|
+
"@aponiajs/platform-elysia": "1.0.0-beta.64",
|
|
52
|
+
"@aponiajs/platform-h3": "1.0.0-beta.64",
|
|
53
|
+
"@aponiajs/platform-hono": "1.0.0-beta.64",
|
|
54
|
+
"@aponiajs/serverless": "1.0.0-beta.64",
|
|
55
|
+
"elysia": "2.0.0-rc.4"
|
|
56
|
+
},
|
|
57
|
+
"engines": {
|
|
58
|
+
"bun": ">=1.4.4"
|
|
59
|
+
}
|
|
60
|
+
}
|