@telamonjs/auth 1.3.0 → 1.4.1
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 +17 -0
- package/README.md +63 -4
- package/dist/{chunk-TL5OYB5P.js → chunk-G73ASFMN.js} +6 -2
- package/dist/chunk-G73ASFMN.js.map +1 -0
- package/dist/index.cjs +26 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +23 -3
- package/dist/index.d.ts +23 -3
- package/dist/index.js +20 -1
- package/dist/index.js.map +1 -1
- package/dist/{jwt-B_WnKVc1.d.cts → jwt-EyXe_d9K.d.cts} +10 -2
- package/dist/{jwt-B_WnKVc1.d.ts → jwt-EyXe_d9K.d.ts} +10 -2
- package/dist/nest/index.cjs +83 -9
- package/dist/nest/index.cjs.map +1 -1
- package/dist/nest/index.d.cts +91 -6
- package/dist/nest/index.d.ts +91 -6
- package/dist/nest/index.js +77 -8
- package/dist/nest/index.js.map +1 -1
- package/dist/next/index.cjs +13 -4
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.d.cts +6 -3
- package/dist/next/index.d.ts +6 -3
- package/dist/next/index.js +9 -4
- package/dist/next/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-TL5OYB5P.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.4.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 7289ce5: Stricter session and API-key handling:
|
|
8
|
+
|
|
9
|
+
- API-key guards treat any falsy verifier result (`false`, `0`, `''`, `NaN`) as a rejection, like `null`.
|
|
10
|
+
- An explicit `maxAge` passed to `decodeSessionToken`, `createJwtAuthGuard` or `createAuthCallbacks({ tokenConfig })` is now enforced against the token's issue time. Without one, only the token's own expiry applies, as before.
|
|
11
|
+
- `createJwtAuthGuard` reads the `__Secure-authjs.session-token` cookie first and, while it is present, never falls back to the plain one. APIs served only over HTTPS can pass `cookieNames: ['__Secure-authjs.session-token']`.
|
|
12
|
+
- `createAuthCallbacks` applies an impersonation cookie only to the session that started the impersonation, and only for tokens issued by `createImpersonationToken`. Ending an impersonation also restores the actor's `accessAt`.
|
|
13
|
+
|
|
14
|
+
## 1.4.0
|
|
15
|
+
|
|
16
|
+
### Minor Changes
|
|
17
|
+
|
|
18
|
+
- 77a2ecc: Service-to-service auth with API keys. `@telamonjs/auth/nest` adds `createApiKeyGuard({ verify, header?, bearer?, createException? })` (the verifier's principal goes to `request.servicePrincipal`, `request.user` is untouched, failures are a generic 401, nothing is logged), `staticApiKey(expected, name?)` (constant-time check of one shared secret, closed while unset), and `@AllowServiceToken()` with a new `apiKey` option on `createJwtAuthGuard`, so a marked route accepts a session or a key. The core adds `generateApiKey(prefix?)` and `hashApiKey(key)` (hex sha256, Web Crypto).
|
|
19
|
+
|
|
3
20
|
## 1.3.0
|
|
4
21
|
|
|
5
22
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
<a href="https://github.com/telamonjs/telamonjs"><img alt="TelamonJS" src="https://cdn.jsdelivr.net/gh/telamonjs/telamonjs@main/.github/assets/logo-mark.svg" height="40"></a>
|
|
2
|
+
|
|
1
3
|
# @telamonjs/auth
|
|
2
4
|
|
|
5
|
+
[](https://www.npmjs.com/package/@telamonjs/auth) [](https://github.com/telamonjs/telamonjs/blob/main/LICENSE)
|
|
6
|
+
|
|
3
7
|
The NextAuth v5 ↔ NestJS bridge. This package owns the **shape of the session
|
|
4
8
|
token** (an `@auth/core` JWE), not your login flow: your app's `authorize()`
|
|
5
9
|
still checks credentials. The Next side gets canonical `jwt`/`session`
|
|
@@ -56,7 +60,9 @@ export const JwtAuthGuard = createJwtAuthGuard()
|
|
|
56
60
|
The guard reads the token from `Authorization: Bearer`, then `?token=` (for
|
|
57
61
|
EventSource/SSE, which can't send headers), then the NextAuth cookies. Cookie
|
|
58
62
|
decoding is salt-aware (`__Secure-` names under HTTPS) and reassembles chunked
|
|
59
|
-
cookies.
|
|
63
|
+
cookies. While a `__Secure-` cookie is present, the plain one is never read; an
|
|
64
|
+
HTTPS-only API passes `cookieNames: ['__Secure-authjs.session-token']` so it is
|
|
65
|
+
never read at all. Opt a route out with `@Public()`.
|
|
60
66
|
|
|
61
67
|
The guard is built when its module is imported, before Nest DI and env
|
|
62
68
|
loading. To read the secret late, pass a function (sync or async), called on
|
|
@@ -91,7 +97,9 @@ const token = await createImpersonationToken({ target, actor, logId: log.id })
|
|
|
91
97
|
The impersonation token **is** the API credential: the callbacks swap
|
|
92
98
|
`accessToken` too, so impersonation is not cosmetic. Wire the cookies through
|
|
93
99
|
`createAuthCallbacks({ getImpersonationCookies, clearImpersonationCookies })`.
|
|
94
|
-
|
|
100
|
+
The cookie only applies to the session of the actor who started it (the
|
|
101
|
+
token's `originalUserId`), so another user signing in on the same browser
|
|
102
|
+
keeps their own identity. For immediate revocation, pass `isImpersonationActive` to the guard; tokens
|
|
95
103
|
without a `logId` are then rejected. Without the hook an impersonation token
|
|
96
104
|
stays valid until it expires, and the guard logs a one-time warning (Nest
|
|
97
105
|
`Logger`) the first time it accepts one:
|
|
@@ -157,17 +165,68 @@ reason going to the Nest `Logger`. A thrown error propagates (a 5xx), like
|
|
|
157
165
|
`resolveUser`'s, so a database outage doesn't sign users out. The cache is in
|
|
158
166
|
memory, per process, bounded to 1000 tokens, and never keeps a thrown error.
|
|
159
167
|
|
|
168
|
+
## Service-to-service (API keys)
|
|
169
|
+
|
|
170
|
+
Jobs, CI and other APIs call with a key instead of a session. A route that
|
|
171
|
+
only takes a key:
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
import { createApiKeyGuard, staticApiKey, Public } from '@telamonjs/auth/nest'
|
|
175
|
+
|
|
176
|
+
export const InternalKeyGuard = createApiKeyGuard({
|
|
177
|
+
header: 'x-internal-token', // default 'x-api-key'
|
|
178
|
+
bearer: true, // also read Authorization: Bearer <key>
|
|
179
|
+
verify: staticApiKey(() => process.env.INTERNAL_API_TOKEN, 'jobs'),
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
@Public() @UseGuards(InternalKeyGuard) @Post('emit') emit() {}
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
`verify(key, request)` returns a principal, or `null` (any falsy value) to
|
|
186
|
+
reject (sync or async, so a database lookup fits too). The principal goes to `request.servicePrincipal`;
|
|
187
|
+
`request.user` is left alone. Anything else is a generic 401 (`createException`
|
|
188
|
+
applies); the guard logs nothing, and a thrown verifier error propagates.
|
|
189
|
+
`staticApiKey` compares sha256 digests with `timingSafeEqual` and rejects
|
|
190
|
+
everything while the expected key is unset.
|
|
191
|
+
|
|
192
|
+
A route that takes a session **or** a key: give the session guard `apiKey` and
|
|
193
|
+
mark the route.
|
|
194
|
+
|
|
195
|
+
```ts
|
|
196
|
+
import { AllowServiceToken } from '@telamonjs/auth/nest'
|
|
197
|
+
|
|
198
|
+
export const JwtAuthGuard = createJwtAuthGuard({
|
|
199
|
+
apiKey: { verify: staticApiKey(() => process.env.INTERNAL_API_KEY) },
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
@AllowServiceToken() @Post('send') send() {}
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
A valid key passes; anything else falls through to the session check.
|
|
206
|
+
Unmarked routes never read the key.
|
|
207
|
+
|
|
208
|
+
Keys stored in the database: `generateApiKey(prefix?)` (32 random bytes,
|
|
209
|
+
base64url) and `await hashApiKey(key)` (hex sha256) from the core entry. Store
|
|
210
|
+
the hash, show the key once, look it up by `hashApiKey(key)` in `verify`.
|
|
211
|
+
Scopes, rotation and audit logging stay in your app.
|
|
212
|
+
|
|
160
213
|
## Core (isomorphic)
|
|
161
214
|
|
|
162
215
|
```ts
|
|
163
216
|
encodeSessionToken(payload, config?) // JwtPayload → JWE string
|
|
164
217
|
decodeSessionToken(token, config?) // → JwtPayload | null (invalid or expired)
|
|
165
218
|
payloadToAuthUser(payload) // claims → typed AuthUser
|
|
219
|
+
generateApiKey(prefix?) // random URL-safe API key
|
|
220
|
+
hashApiKey(key) // → Promise<hex sha256>, to store
|
|
166
221
|
```
|
|
167
222
|
|
|
168
223
|
`TokenConfig` is `{ secret?, salt?, maxAge? }`. Defaults: salt
|
|
169
224
|
`'authjs.session-token'` (`DEFAULT_SALT`), maxAge 24 h (`DEFAULT_MAX_AGE`),
|
|
170
|
-
impersonation 1 h (`DEFAULT_IMPERSONATION_MAX_AGE`).
|
|
225
|
+
impersonation 1 h (`DEFAULT_IMPERSONATION_MAX_AGE`). Those maxAge defaults
|
|
226
|
+
set the lifetime of the tokens you encode. On the decoding side
|
|
227
|
+
(`decodeSessionToken`, the guard, `createAuthCallbacks({ tokenConfig })`) a
|
|
228
|
+
`maxAge` you pass also rejects a token issued longer ago than that; without
|
|
229
|
+
one, the token's own `exp` is the only limit.
|
|
171
230
|
|
|
172
231
|
`AuthUser` structurally satisfies `UserWithPermissions` from
|
|
173
232
|
[`@telamonjs/permissions`](https://www.npmjs.com/package/@telamonjs/permissions),
|
|
@@ -186,5 +245,5 @@ Every name each entry point exports, runtime and types: [Public API index](https
|
|
|
186
245
|
|
|
187
246
|
## Full docs
|
|
188
247
|
|
|
189
|
-
**Full docs →** [the auth page of the docs site](https://
|
|
248
|
+
**Full docs →** [the auth page of the docs site](https://telamonjs.com/docs/packages/auth)
|
|
190
249
|
(MDX sources, readable on GitHub).
|
|
@@ -51,7 +51,11 @@ async function decodeSessionToken(token, config) {
|
|
|
51
51
|
const { secret, salt } = resolveTokenConfig(config);
|
|
52
52
|
try {
|
|
53
53
|
const payload = await decode({ token, secret, salt });
|
|
54
|
-
|
|
54
|
+
if (!payload) return null;
|
|
55
|
+
if (config?.maxAge != null && (payload.iat ?? 0) + config.maxAge < Date.now() / 1e3) {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
return payload;
|
|
55
59
|
} catch {
|
|
56
60
|
return null;
|
|
57
61
|
}
|
|
@@ -99,4 +103,4 @@ export {
|
|
|
99
103
|
decodeSessionToken,
|
|
100
104
|
payloadToAuthUser
|
|
101
105
|
};
|
|
102
|
-
//# sourceMappingURL=chunk-
|
|
106
|
+
//# sourceMappingURL=chunk-G73ASFMN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/session.ts","../src/jwt.ts"],"sourcesContent":["/**\n * Session freshness & revocation — pure, isomorphic, DB-agnostic.\n *\n * Roles/permissions are materialized in the session token, so a change in the\n * database only reaches the token at the next login, and a token cannot be\n * revoked by itself. The app keeps two per-user timestamps (e.g.\n * `accessChangedAt`, `sessionsRevokedAt`) and compares them with the times\n * stamped into the token at login; these helpers do the comparison.\n */\n\n/** Login/claims times stamped into the session token. */\nexport interface SessionTimes {\n /** Login time, epoch ms */\n authTime?: number\n /** When roles/permissions in the token were computed, epoch ms */\n accessAt?: number\n}\n\n/** Per-user marks the app stores. `null`/`undefined` mean \"nothing changed\". */\nexport interface SessionMarks {\n /** Every session that logged in before this instant is revoked */\n revokedAt?: Date | number | null\n /** Roles/permissions changed at this instant */\n accessChangedAt?: Date | number | null\n}\n\n/**\n * - `revoked`: the session must end (sign out / 401)\n * - `stale`: the session is valid, but its roles/permissions must be recomputed\n * - `fresh`: the token is up to date\n */\nexport type SessionState = 'revoked' | 'stale' | 'fresh'\n\n/** Stamps `authTime` and `accessAt` (epoch ms). Mutates and returns the token. */\nexport function stampSessionTimes<T extends object>(\n token: T,\n now: number = Date.now()\n): T & Required<SessionTimes> {\n return Object.assign(token, { authTime: now, accessAt: now })\n}\n\nfunction toMs(mark: Date | number | null | undefined): number | null {\n if (mark == null) return null\n return typeof mark === 'number' ? mark : mark.getTime()\n}\n\n/**\n * Compares the token's times with the user's marks. Revoked wins over stale.\n * A missing claim counts as 0, so tokens issued before adoption are caught by\n * the next revocation/access change.\n */\nexport function sessionState(\n token: SessionTimes,\n marks: SessionMarks\n): SessionState {\n const revokedAt = toMs(marks.revokedAt)\n if (revokedAt !== null && revokedAt > (token.authTime ?? 0)) return 'revoked'\n const accessChangedAt = toMs(marks.accessChangedAt)\n if (accessChangedAt !== null && accessChangedAt > (token.accessAt ?? 0)) {\n return 'stale'\n }\n return 'fresh'\n}\n","import { encode, decode } from '@auth/core/jwt'\nimport { stampSessionTimes } from './session'\nimport type { AuthUser, MfJwtPayload, RoleInfo } from './types'\n\nexport interface TokenConfig {\n /** Default: process.env.AUTH_SECRET || process.env.NEXTAUTH_SECRET */\n secret?: string\n /**\n * Key-derivation salt for the JWE — it MUST be identical on both sides.\n * Default: 'authjs.session-token' (NextAuth v5). Projects on the legacy\n * v4 cookie use 'next-auth.session-token'.\n */\n salt?: string\n /**\n * Seconds. Encoding: the token lifetime, default 24h. Decoding (and the\n * guard): only when set, rejects a token issued longer ago than this;\n * unset, the token's own `exp` is the only limit.\n */\n maxAge?: number\n}\n\nexport const DEFAULT_SALT = 'authjs.session-token'\nexport const DEFAULT_MAX_AGE = 24 * 60 * 60\n\nexport function resolveTokenConfig(\n config?: TokenConfig\n): Required<TokenConfig> {\n const secret =\n config?.secret ?? process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET\n if (!secret) {\n throw new Error('AUTH_SECRET or NEXTAUTH_SECRET must be defined')\n }\n return {\n secret,\n salt: config?.salt ?? DEFAULT_SALT,\n maxAge: config?.maxAge ?? DEFAULT_MAX_AGE,\n }\n}\n\n/**\n * Issues the session JWE in the NextAuth v5 format (for server-side login on\n * the API, impersonation, etc.). Same secret+salt as the Next app.\n *\n * A payload without `authTime` is a new session: it gets `authTime`/`accessAt`\n * stamped (on a copy), so `sessionState` does not read it as issued at 0.\n */\nexport async function encodeSessionToken(\n payload: MfJwtPayload,\n config?: TokenConfig\n): Promise<string> {\n const { secret, salt, maxAge } = resolveTokenConfig(config)\n const token =\n payload.authTime == null ? stampSessionTimes({ ...payload }) : payload\n return encode({ token, secret, salt, maxAge })\n}\n\n/**\n * Decodes the session JWE. Returns null for an invalid/expired token.\n * An explicit `config.maxAge` also rejects a token issued (`iat`) more than\n * that many seconds ago; without it, only the token's own `exp` applies.\n */\nexport async function decodeSessionToken(\n token: string,\n config?: TokenConfig\n): Promise<MfJwtPayload | null> {\n const { secret, salt } = resolveTokenConfig(config)\n try {\n const payload = (await decode({ token, secret, salt })) as MfJwtPayload | null\n if (!payload) return null\n // A token without iat counts as issued at 0: fail closed\n if (config?.maxAge != null && (payload.iat ?? 0) + config.maxAge < Date.now() / 1000) {\n return null\n }\n return payload\n } catch {\n return null\n }\n}\n\n/**\n * Maps the JWT payload to the request's AuthUser,\n * including the impersonation block.\n */\nexport function payloadToAuthUser(payload: MfJwtPayload): AuthUser {\n const role = payload.role as RoleInfo\n const roles = payload.roles ?? (role ? [role] : [])\n const user: AuthUser = {\n id: payload.id,\n pessoaId: payload.pessoaId ? String(payload.pessoaId) : undefined,\n name: payload.name,\n email: payload.email,\n role,\n roles,\n permissions: payload.permissions ?? [],\n sessionId: payload.sid ?? payload.jti,\n }\n\n if (payload.clienteIds) {\n user.clienteIds = payload.clienteIds\n }\n\n if (payload.impersonatedUserId) {\n const origRole = payload.originalUserRole as RoleInfo\n const origRoles = payload.originalUserRoles ?? (origRole ? [origRole] : [])\n user.isImpersonating = true\n user.impersonationLogId = payload.impersonationLogId\n user.originalUser = {\n id: payload.originalUserId as string,\n name: payload.originalUserName as string,\n email: payload.originalUserEmail as string,\n role: origRole,\n roles: origRoles,\n }\n }\n\n return user\n}\n"],"mappings":";;;;;;;;;;;;AAkCO,SAAS,kBACd,OACA,MAAc,KAAK,IAAI,GACK;AAC5B,SAAO,OAAO,OAAO,OAAO,EAAE,UAAU,KAAK,UAAU,IAAI,CAAC;AAC9D;AAEA,SAAS,KAAK,MAAuD;AACnE,MAAI,QAAQ,KAAM,QAAO;AACzB,SAAO,OAAO,SAAS,WAAW,OAAO,KAAK,QAAQ;AACxD;AAOO,SAAS,aACd,OACA,OACc;AACd,QAAM,YAAY,KAAK,MAAM,SA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jD,QAAM,OAAiB;AAAA,IACrB,IAAI,QAAQ;AAAA,IACZ,UAAU,QAAQ,WAAW,OAAO,QAAQ,QAAQ,IAAI;AAAA,IACxD,MAAM,QAAQ;AAAA,IACd,OAAO,QAAQ;AAAA,IACf;AAAA,IACA;AAAA,IACA,aAAa,QAAQ,eAAe,CAAC;AAAA,IACrC,WAAW,QAAQ,OAAO,QAAQ;AAAA,EACpC;AAEA,MAAI,QAAQ,YAAY;AACtB,SAAK,aAAa,QAAQ;AAAA,EAC5B;AAEA,MAAI,QAAQ,oBAAoB;AAC9B,UAAM,WAAW,QAAQ;AACzB,UAAM,YAAY,QAAQ,sBAAsB,WAAW,CAAC,QAAQ,IAAI,CAAC;AACzE,SAAK,kBAAkB;AACvB,SAAK,qBAAqB,QAAQ;AAClC,SAAK,eAAe;AAAA,MAClB,IAAI,QAAQ;AAAA,MACZ,MAAM,QAAQ;AAAA,MACd,OAAO,QAAQ;AAAA,MACf,MAAM;AAAA,MACN,OAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
|
package/dist/index.cjs
CHANGED
|
@@ -26,6 +26,8 @@ __export(src_exports, {
|
|
|
26
26
|
createImpersonationToken: () => createImpersonationToken,
|
|
27
27
|
decodeSessionToken: () => decodeSessionToken,
|
|
28
28
|
encodeSessionToken: () => encodeSessionToken,
|
|
29
|
+
generateApiKey: () => generateApiKey,
|
|
30
|
+
hashApiKey: () => hashApiKey,
|
|
29
31
|
payloadToAuthUser: () => payloadToAuthUser,
|
|
30
32
|
resolveTokenConfig: () => resolveTokenConfig,
|
|
31
33
|
sessionState: () => sessionState,
|
|
@@ -77,7 +79,11 @@ async function decodeSessionToken(token, config) {
|
|
|
77
79
|
const { secret, salt } = resolveTokenConfig(config);
|
|
78
80
|
try {
|
|
79
81
|
const payload = await (0, import_jwt.decode)({ token, secret, salt });
|
|
80
|
-
|
|
82
|
+
if (!payload) return null;
|
|
83
|
+
if (config?.maxAge != null && (payload.iat ?? 0) + config.maxAge < Date.now() / 1e3) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
return payload;
|
|
81
87
|
} catch {
|
|
82
88
|
return null;
|
|
83
89
|
}
|
|
@@ -148,6 +154,23 @@ async function createImpersonationToken({
|
|
|
148
154
|
maxAge: maxAge ?? config?.maxAge ?? DEFAULT_IMPERSONATION_MAX_AGE
|
|
149
155
|
});
|
|
150
156
|
}
|
|
157
|
+
|
|
158
|
+
// src/api-key.ts
|
|
159
|
+
function generateApiKey(prefix = "") {
|
|
160
|
+
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(32));
|
|
161
|
+
const base64 = btoa(String.fromCharCode(...bytes));
|
|
162
|
+
return prefix + base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
163
|
+
}
|
|
164
|
+
async function hashApiKey(key) {
|
|
165
|
+
const digest = await globalThis.crypto.subtle.digest(
|
|
166
|
+
"SHA-256",
|
|
167
|
+
new TextEncoder().encode(key)
|
|
168
|
+
);
|
|
169
|
+
return Array.from(
|
|
170
|
+
new Uint8Array(digest),
|
|
171
|
+
(b) => b.toString(16).padStart(2, "0")
|
|
172
|
+
).join("");
|
|
173
|
+
}
|
|
151
174
|
// Annotate the CommonJS export names for ESM import in node:
|
|
152
175
|
0 && (module.exports = {
|
|
153
176
|
DEFAULT_IMPERSONATION_MAX_AGE,
|
|
@@ -156,6 +179,8 @@ async function createImpersonationToken({
|
|
|
156
179
|
createImpersonationToken,
|
|
157
180
|
decodeSessionToken,
|
|
158
181
|
encodeSessionToken,
|
|
182
|
+
generateApiKey,
|
|
183
|
+
hashApiKey,
|
|
159
184
|
payloadToAuthUser,
|
|
160
185
|
resolveTokenConfig,
|
|
161
186
|
sessionState,
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/jwt.ts","../src/session.ts","../src/impersonation.ts"],"sourcesContent":["/**\n * @telamonjs/auth — NextAuth v5 ↔ NestJS auth bridge.\n *\n * Isomorphic core: the session token contract (JWE @auth/core) shared\n * between the Next app and the Nest API. The login authorize() belongs to\n * the app; this package owns the token format, not the login flow.\n *\n * NestJS side (guard + @Public): '@telamonjs/auth/nest'.\n * Next side (callbacks): '@telamonjs/auth/next'.\n */\n\nexport {\n encodeSessionToken,\n decodeSessionToken,\n payloadToAuthUser,\n resolveTokenConfig,\n DEFAULT_SALT,\n DEFAULT_MAX_AGE,\n type TokenConfig,\n} from './jwt'\n\nexport {\n createImpersonationToken,\n DEFAULT_IMPERSONATION_MAX_AGE,\n type ImpersonationParty,\n type CreateImpersonationTokenInput,\n} from './impersonation'\n\nexport {\n stampSessionTimes,\n sessionState,\n type SessionState,\n type SessionMarks,\n type SessionTimes,\n} from './session'\n\nexport type { RoleInfo, AuthUser, MfJwtPayload, JwtPayload } from './types'\n","import { encode, decode } from '@auth/core/jwt'\nimport { stampSessionTimes } from './session'\nimport type { AuthUser, MfJwtPayload, RoleInfo } from './types'\n\nexport interface TokenConfig {\n /** Default: process.env.AUTH_SECRET || process.env.NEXTAUTH_SECRET */\n secret?: string\n /**\n * Key-derivation salt for the JWE — it MUST be identical on both sides.\n * Default: 'authjs.session-token' (NextAuth v5). Projects on the legacy\n * v4 cookie use 'next-auth.session-token'.\n */\n salt?: string\n /** Seconds. Default: 24h */\n maxAge?: number\n}\n\nexport const DEFAULT_SALT = 'authjs.session-token'\nexport const DEFAULT_MAX_AGE = 24 * 60 * 60\n\nexport function resolveTokenConfig(\n config?: TokenConfig\n): Required<TokenConfig> {\n const secret =\n config?.secret ?? process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET\n if (!secret) {\n throw new Error('AUTH_SECRET or NEXTAUTH_SECRET must be defined')\n }\n return {\n secret,\n salt: config?.salt ?? DEFAULT_SALT,\n maxAge: config?.maxAge ?? DEFAULT_MAX_AGE,\n }\n}\n\n/**\n * Issues the session JWE in the NextAuth v5 format (for server-side login on\n * the API, impersonation, etc.). Same secret+salt as the Next app.\n *\n * A payload without `authTime` is a new session: it gets `authTime`/`accessAt`\n * stamped (on a copy), so `sessionState` does not read it as issued at 0.\n */\nexport async function encodeSessionToken(\n payload: MfJwtPayload,\n config?: TokenConfig\n): Promise<string> {\n const { secret, salt, maxAge } = resolveTokenConfig(config)\n const token =\n payload.authTime == null ? stampSessionTimes({ ...payload }) : payload\n return encode({ token, secret, salt, maxAge })\n}\n\n/** Decodes the session JWE. Returns null for an invalid/expired token. */\nexport async function decodeSessionToken(\n token: string,\n config?: TokenConfig\n): Promise<MfJwtPayload | null> {\n const { secret, salt } = resolveTokenConfig(config)\n try {\n const payload = await decode({ token, secret, salt })\n return (payload as MfJwtPayload | null) ?? null\n } catch {\n return null\n }\n}\n\n/**\n * Maps the JWT payload to the request's AuthUser,\n * including the impersonation block.\n */\nexport function payloadToAuthUser(payload: MfJwtPayload): AuthUser {\n const role = payload.role as RoleInfo\n const roles = payload.roles ?? (role ? [role] : [])\n const user: AuthUser = {\n id: payload.id,\n pessoaId: payload.pessoaId ? String(payload.pessoaId) : undefined,\n name: payload.name,\n email: payload.email,\n role,\n roles,\n permissions: payload.permissions ?? [],\n sessionId: payload.sid ?? payload.jti,\n }\n\n if (payload.clienteIds) {\n user.clienteIds = payload.clienteIds\n }\n\n if (payload.impersonatedUserId) {\n const origRole = payload.originalUserRole as RoleInfo\n const origRoles = payload.originalUserRoles ?? (origRole ? [origRole] : [])\n user.isImpersonating = true\n user.impersonationLogId = payload.impersonationLogId\n user.originalUser = {\n id: payload.originalUserId as string,\n name: payload.originalUserName as string,\n email: payload.originalUserEmail as string,\n role: origRole,\n roles: origRoles,\n }\n }\n\n return user\n}\n","/**\n * Session freshness & revocation — pure, isomorphic, DB-agnostic.\n *\n * Roles/permissions are materialized in the session token, so a change in the\n * database only reaches the token at the next login, and a token cannot be\n * revoked by itself. The app keeps two per-user timestamps (e.g.\n * `accessChangedAt`, `sessionsRevokedAt`) and compares them with the times\n * stamped into the token at login; these helpers do the comparison.\n */\n\n/** Login/claims times stamped into the session token. */\nexport interface SessionTimes {\n /** Login time, epoch ms */\n authTime?: number\n /** When roles/permissions in the token were computed, epoch ms */\n accessAt?: number\n}\n\n/** Per-user marks the app stores. `null`/`undefined` mean \"nothing changed\". */\nexport interface SessionMarks {\n /** Every session that logged in before this instant is revoked */\n revokedAt?: Date | number | null\n /** Roles/permissions changed at this instant */\n accessChangedAt?: Date | number | null\n}\n\n/**\n * - `revoked`: the session must end (sign out / 401)\n * - `stale`: the session is valid, but its roles/permissions must be recomputed\n * - `fresh`: the token is up to date\n */\nexport type SessionState = 'revoked' | 'stale' | 'fresh'\n\n/** Stamps `authTime` and `accessAt` (epoch ms). Mutates and returns the token. */\nexport function stampSessionTimes<T extends object>(\n token: T,\n now: number = Date.now()\n): T & Required<SessionTimes> {\n return Object.assign(token, { authTime: now, accessAt: now })\n}\n\nfunction toMs(mark: Date | number | null | undefined): number | null {\n if (mark == null) return null\n return typeof mark === 'number' ? mark : mark.getTime()\n}\n\n/**\n * Compares the token's times with the user's marks. Revoked wins over stale.\n * A missing claim counts as 0, so tokens issued before adoption are caught by\n * the next revocation/access change.\n */\nexport function sessionState(\n token: SessionTimes,\n marks: SessionMarks\n): SessionState {\n const revokedAt = toMs(marks.revokedAt)\n if (revokedAt !== null && revokedAt > (token.authTime ?? 0)) return 'revoked'\n const accessChangedAt = toMs(marks.accessChangedAt)\n if (accessChangedAt !== null && accessChangedAt > (token.accessAt ?? 0)) {\n return 'stale'\n }\n return 'fresh'\n}\n","import { encodeSessionToken, type TokenConfig } from './jwt'\nimport type { MfJwtPayload, RoleInfo } from './types'\n\n/** Seconds. Impersonation token default: 1h (the normal session is 24h). */\nexport const DEFAULT_IMPERSONATION_MAX_AGE = 60 * 60\n\n/**\n * Data for one side of the impersonation, ALREADY RESOLVED by the app.\n * The package never touches the database — loading the user/roles/permissions\n * is the app's job.\n */\nexport interface ImpersonationParty {\n id: string\n pessoaId?: string\n name?: string\n email: string\n role: RoleInfo\n roles?: RoleInfo[]\n permissions?: string[]\n}\n\nexport interface CreateImpersonationTokenInput {\n /** User being impersonated — becomes the subject of the token. */\n target: ImpersonationParty & { permissions: string[] }\n /** Admin who started it (becomes the `original*` block). */\n actor: ImpersonationParty\n /** Id of the app's audit record (used by the revocation check in the guard). */\n logId: string\n /** Seconds. Default: `DEFAULT_IMPERSONATION_MAX_AGE` (1h). */\n maxAge?: number\n /**\n * Includes `originalPermissions` in the token. Default: false — it only\n * bloats the payload (chunked cookie) and nothing in the package reads\n * those permissions.\n */\n includeOriginalPermissions?: boolean\n}\n\n/**\n * Issues the impersonation token: a session JWE whose SUBJECT is the target\n * and which carries the actor in the `original*` claims — exactly the shape\n * `payloadToAuthUser` reads back (`isImpersonating` + `originalUser`).\n *\n * The token doubles as a credential: sent as `Authorization: Bearer` it\n * authenticates as the target on the API, with `impersonationLogId` for\n * revocation.\n *\n * ```ts\n * const token = await createImpersonationToken({ target, actor, logId: log.id })\n * ```\n *\n * `iat`/`exp`/`jti` are written by `@auth/core/jwt.encode` — the TTL goes\n * through `maxAge`, never as a claim in the payload.\n */\nexport async function createImpersonationToken(\n {\n target,\n actor,\n logId,\n maxAge,\n includeOriginalPermissions,\n }: CreateImpersonationTokenInput,\n config?: TokenConfig\n): Promise<string> {\n const payload: MfJwtPayload = {\n sub: target.id,\n id: target.id,\n pessoaId: target.pessoaId,\n name: target.name,\n email: target.email,\n role: target.role,\n roles: target.roles ?? [target.role],\n permissions: target.permissions ?? [],\n\n impersonatedUserId: target.id,\n impersonationLogId: logId,\n originalUserId: actor.id,\n originalUserName: actor.name,\n originalUserEmail: actor.email,\n originalUserRole: actor.role,\n originalUserRoles: actor.roles ?? [actor.role],\n }\n\n if (includeOriginalPermissions) {\n payload.originalPermissions = actor.permissions ?? []\n }\n\n return encodeSessionToken(payload, {\n ...config,\n maxAge: maxAge ?? config?.maxAge ?? DEFAULT_IMPERSONATION_MAX_AGE,\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA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a,OAAO,eAAe,CAAC;AAAA,IAEpC,oBAAoB,OAAO;AAAA,IAC3B,oBAAoB;AAAA,IACpB,gBAAgB,MAAM;AAAA,IACtB,kBAAkB,MAAM;AAAA,IACxB,mBAAmB,MAAM;AAAA,IACzB,kBAAkB,MAAM;AAAA,IACxB,mBAAmB,MAAM,SAAS,CAAC,MAAM,IAAI;AAAA,EAC/C;AAEA,MAAI,4BAA4B;AAC9B,YAAQ,sBAAsB,MAAM,eAAe,CAAC;AAAA,EACtD;AAEA,SAAO,mBAAmB,SAAS;AAAA,IACjC,GAAG;AAAA,IACH,QAAQ,UAAU,QAAQ,UAAU;AAAA,EACtC,CAAC;AACH;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/jwt.ts","../src/session.ts","../src/impersonation.ts","../src/api-key.ts"],"sourcesContent":["/**\n * @telamonjs/auth — NextAuth v5 ↔ NestJS auth bridge.\n *\n * Isomorphic core: the session token contract (JWE @auth/core) shared\n * between the Next app and the Nest API. The login authorize() belongs to\n * the app; this package owns the token format, not the login flow.\n *\n * NestJS side (guard + @Public): '@telamonjs/auth/nest'.\n * Next side (callbacks): '@telamonjs/auth/next'.\n */\n\nexport {\n encodeSessionToken,\n decodeSessionToken,\n payloadToAuthUser,\n resolveTokenConfig,\n DEFAULT_SALT,\n DEFAULT_MAX_AGE,\n type TokenConfig,\n} from './jwt'\n\nexport {\n createImpersonationToken,\n DEFAULT_IMPERSONATION_MAX_AGE,\n type ImpersonationParty,\n type CreateImpersonationTokenInput,\n} from './impersonation'\n\nexport {\n stampSessionTimes,\n sessionState,\n type SessionState,\n type SessionMarks,\n type SessionTimes,\n} from './session'\n\nexport { generateApiKey, hashApiKey } from './api-key'\n\nexport type { RoleInfo, AuthUser, MfJwtPayload, JwtPayload } from './types'\n","import { encode, decode } from '@auth/core/jwt'\nimport { stampSessionTimes } from './session'\nimport type { AuthUser, MfJwtPayload, RoleInfo } from './types'\n\nexport interface TokenConfig {\n /** Default: process.env.AUTH_SECRET || process.env.NEXTAUTH_SECRET */\n secret?: string\n /**\n * Key-derivation salt for the JWE — it MUST be identical on both sides.\n * Default: 'authjs.session-token' (NextAuth v5). Projects on the legacy\n * v4 cookie use 'next-auth.session-token'.\n */\n salt?: string\n /**\n * Seconds. Encoding: the token lifetime, default 24h. Decoding (and the\n * guard): only when set, rejects a token issued longer ago than this;\n * unset, the token's own `exp` is the only limit.\n */\n maxAge?: number\n}\n\nexport const DEFAULT_SALT = 'authjs.session-token'\nexport const DEFAULT_MAX_AGE = 24 * 60 * 60\n\nexport function resolveTokenConfig(\n config?: TokenConfig\n): Required<TokenConfig> {\n const secret =\n config?.secret ?? process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET\n if (!secret) {\n throw new Error('AUTH_SECRET or NEXTAUTH_SECRET must be defined')\n }\n return {\n secret,\n salt: config?.salt ?? DEFAULT_SALT,\n maxAge: config?.maxAge ?? DEFAULT_MAX_AGE,\n }\n}\n\n/**\n * Issues the session JWE in the NextAuth v5 format (for server-side login on\n * the API, impersonation, etc.). Same secret+salt as the Next app.\n *\n * A payload without `authTime` is a new session: it gets `authTime`/`accessAt`\n * stamped (on a copy), so `sessionState` does not read it as issued at 0.\n */\nexport async function encodeSessionToken(\n payload: MfJwtPayload,\n config?: TokenConfig\n): Promise<string> {\n const { secret, salt, maxAge } = resolveTokenConfig(config)\n const token =\n payload.authTime == null ? stampSessionTimes({ ...payload }) : payload\n return encode({ token, secret, salt, maxAge })\n}\n\n/**\n * Decodes the session JWE. Returns null for an invalid/expired token.\n * An explicit `config.maxAge` also rejects a token issued (`iat`) more than\n * that many seconds ago; without it, only the token's own `exp` applies.\n */\nexport async function decodeSessionToken(\n token: string,\n config?: TokenConfig\n): Promise<MfJwtPayload | null> {\n const { secret, salt } = resolveTokenConfig(config)\n try {\n const payload = (await decode({ token, secret, salt })) as MfJwtPayload | null\n if (!payload) return null\n // A token without iat counts as issued at 0: fail closed\n if (config?.maxAge != null && (payload.iat ?? 0) + config.maxAge < Date.now() / 1000) {\n return null\n }\n return payload\n } catch {\n return null\n }\n}\n\n/**\n * Maps the JWT payload to the request's AuthUser,\n * including the impersonation block.\n */\nexport function payloadToAuthUser(payload: MfJwtPayload): AuthUser {\n const role = payload.role as RoleInfo\n const roles = payload.roles ?? (role ? [role] : [])\n const user: AuthUser = {\n id: payload.id,\n pessoaId: payload.pessoaId ? String(payload.pessoaId) : undefined,\n name: payload.name,\n email: payload.email,\n role,\n roles,\n permissions: payload.permissions ?? [],\n sessionId: payload.sid ?? payload.jti,\n }\n\n if (payload.clienteIds) {\n user.clienteIds = payload.clienteIds\n }\n\n if (payload.impersonatedUserId) {\n const origRole = payload.originalUserRole as RoleInfo\n const origRoles = payload.originalUserRoles ?? (origRole ? [origRole] : [])\n user.isImpersonating = true\n user.impersonationLogId = payload.impersonationLogId\n user.originalUser = {\n id: payload.originalUserId as string,\n name: payload.originalUserName as string,\n email: payload.originalUserEmail as string,\n role: origRole,\n roles: origRoles,\n }\n }\n\n return user\n}\n","/**\n * Session freshness & revocation — pure, isomorphic, DB-agnostic.\n *\n * Roles/permissions are materialized in the session token, so a change in the\n * database only reaches the token at the next login, and a token cannot be\n * revoked by itself. The app keeps two per-user timestamps (e.g.\n * `accessChangedAt`, `sessionsRevokedAt`) and compares them with the times\n * stamped into the token at login; these helpers do the comparison.\n */\n\n/** Login/claims times stamped into the session token. */\nexport interface SessionTimes {\n /** Login time, epoch ms */\n authTime?: number\n /** When roles/permissions in the token were computed, epoch ms */\n accessAt?: number\n}\n\n/** Per-user marks the app stores. `null`/`undefined` mean \"nothing changed\". */\nexport interface SessionMarks {\n /** Every session that logged in before this instant is revoked */\n revokedAt?: Date | number | null\n /** Roles/permissions changed at this instant */\n accessChangedAt?: Date | number | null\n}\n\n/**\n * - `revoked`: the session must end (sign out / 401)\n * - `stale`: the session is valid, but its roles/permissions must be recomputed\n * - `fresh`: the token is up to date\n */\nexport type SessionState = 'revoked' | 'stale' | 'fresh'\n\n/** Stamps `authTime` and `accessAt` (epoch ms). Mutates and returns the token. */\nexport function stampSessionTimes<T extends object>(\n token: T,\n now: number = Date.now()\n): T & Required<SessionTimes> {\n return Object.assign(token, { authTime: now, accessAt: now })\n}\n\nfunction toMs(mark: Date | number | null | undefined): number | null {\n if (mark == null) return null\n return typeof mark === 'number' ? mark : mark.getTime()\n}\n\n/**\n * Compares the token's times with the user's marks. Revoked wins over stale.\n * A missing claim counts as 0, so tokens issued before adoption are caught by\n * the next revocation/access change.\n */\nexport function sessionState(\n token: SessionTimes,\n marks: SessionMarks\n): SessionState {\n const revokedAt = toMs(marks.revokedAt)\n if (revokedAt !== null && revokedAt > (token.authTime ?? 0)) return 'revoked'\n const accessChangedAt = toMs(marks.accessChangedAt)\n if (accessChangedAt !== null && accessChangedAt > (token.accessAt ?? 0)) {\n return 'stale'\n }\n return 'fresh'\n}\n","import { encodeSessionToken, type TokenConfig } from './jwt'\nimport type { MfJwtPayload, RoleInfo } from './types'\n\n/** Seconds. Impersonation token default: 1h (the normal session is 24h). */\nexport const DEFAULT_IMPERSONATION_MAX_AGE = 60 * 60\n\n/**\n * Data for one side of the impersonation, ALREADY RESOLVED by the app.\n * The package never touches the database — loading the user/roles/permissions\n * is the app's job.\n */\nexport interface ImpersonationParty {\n id: string\n pessoaId?: string\n name?: string\n email: string\n role: RoleInfo\n roles?: RoleInfo[]\n permissions?: string[]\n}\n\nexport interface CreateImpersonationTokenInput {\n /** User being impersonated — becomes the subject of the token. */\n target: ImpersonationParty & { permissions: string[] }\n /** Admin who started it (becomes the `original*` block). */\n actor: ImpersonationParty\n /** Id of the app's audit record (used by the revocation check in the guard). */\n logId: string\n /** Seconds. Default: `DEFAULT_IMPERSONATION_MAX_AGE` (1h). */\n maxAge?: number\n /**\n * Includes `originalPermissions` in the token. Default: false — it only\n * bloats the payload (chunked cookie) and nothing in the package reads\n * those permissions.\n */\n includeOriginalPermissions?: boolean\n}\n\n/**\n * Issues the impersonation token: a session JWE whose SUBJECT is the target\n * and which carries the actor in the `original*` claims — exactly the shape\n * `payloadToAuthUser` reads back (`isImpersonating` + `originalUser`).\n *\n * The token doubles as a credential: sent as `Authorization: Bearer` it\n * authenticates as the target on the API, with `impersonationLogId` for\n * revocation.\n *\n * ```ts\n * const token = await createImpersonationToken({ target, actor, logId: log.id })\n * ```\n *\n * `iat`/`exp`/`jti` are written by `@auth/core/jwt.encode` — the TTL goes\n * through `maxAge`, never as a claim in the payload.\n */\nexport async function createImpersonationToken(\n {\n target,\n actor,\n logId,\n maxAge,\n includeOriginalPermissions,\n }: CreateImpersonationTokenInput,\n config?: TokenConfig\n): Promise<string> {\n const payload: MfJwtPayload = {\n sub: target.id,\n id: target.id,\n pessoaId: target.pessoaId,\n name: target.name,\n email: target.email,\n role: target.role,\n roles: target.roles ?? [target.role],\n permissions: target.permissions ?? [],\n\n impersonatedUserId: target.id,\n impersonationLogId: logId,\n originalUserId: actor.id,\n originalUserName: actor.name,\n originalUserEmail: actor.email,\n originalUserRole: actor.role,\n originalUserRoles: actor.roles ?? [actor.role],\n }\n\n if (includeOriginalPermissions) {\n payload.originalPermissions = actor.permissions ?? []\n }\n\n return encodeSessionToken(payload, {\n ...config,\n maxAge: maxAge ?? config?.maxAge ?? DEFAULT_IMPERSONATION_MAX_AGE,\n })\n}\n","/**\n * API key helpers for machine-to-machine calls. Isomorphic (Web Crypto, no\n * `node:crypto`), so the core entry still loads in the browser and on the edge.\n * The Nest guard that checks keys lives in '@telamonjs/auth/nest'.\n */\n\n/**\n * A new random API key: 32 bytes as URL-safe base64 (43 characters), after\n * an optional `prefix` (e.g. `'svc_'`, so a leaked key is recognizable).\n * Show it once; store it in an env var, or store `hashApiKey(key)` in the\n * database.\n */\nexport function generateApiKey(prefix = ''): string {\n const bytes = globalThis.crypto.getRandomValues(new Uint8Array(32))\n const base64 = btoa(String.fromCharCode(...bytes))\n return (\n prefix +\n base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n )\n}\n\n/**\n * The hex sha256 of a key — what to store and look up instead of the key\n * itself. Same digest as `createHash('sha256').update(key).digest('hex')`.\n * A random 32-byte key needs no salt or slow hash: there is nothing to\n * brute-force.\n */\nexport async function hashApiKey(key: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(key)\n )\n return Array.from(new Uint8Array(digest), b =>\n b.toString(16).padStart(2, '0')\n ).join('')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAA+B;;;ACkCxB,SAAS,kBACd,OACA,MAAc,KAAK,IAAI,GACK;AAC5B,SAAO,OAAO,OAAO,OAAO,EAAE,UAAU,KAAK,UAAU,IAAI,CAAC;AAC9D;AAEA,SAAS,KAAK,MAAuD;AACnE,MAAI,QAAQ,KAAM,QAAO;AACzB,SAAO,OAAO,SAAS,WAAW,OAAO,KAAK,QAAQ;AACxD;AAOO,SAAS,aACd,OACA,OACc;AACd,QAAM,YAAY,KAAK,MAAM,SAAS;AACtC,MAAI,cAAc,QAAQ,aAAa,MAAM,YAAY,GAAI,QAAO;AACpE,QAAM,kBAAkB,KAAK,MAAM,eAAe;AAClD,MAAI,oBAAoB,QAAQ,mBAAmB,MAAM,YAAY,IAAI;AACvE,WAAO;AAAA,EACT;AACA,SAAO;AACT;;;ADzCO,IAAM,eAAe;AACrB,IAAM,kBAAkB,KAAK,KAAK;AAElC,SAAS,mBACd,QACuB;AACvB,QAAM,SACJ,QAAQ,UAAU,QAAQ,IAAI,eAAe,QAAQ,IAAI;AAC3D,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,gDAAgD;AAAA,EAClE;AACA,SAAO;AAAA,IACL;AAAA,IACA,MAAM,QAAQ,QAAQ;AAAA,IACtB,QAAQ,QAAQ,UAAU;AAAA,EAC5B;AACF;AASA,eAAsB,mBACpB,SACA,QACiB;AACj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,EAC9B;AACA,SAAO,MAAM;AAAA,IAAK,IAAI,WAAW,MAAM;AAAA,IAAG,OACxC,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AAAA,EAChC,EAAE,KAAK,EAAE;AACX;","names":[]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { R as RoleInfo, T as TokenConfig } from './jwt-
|
|
2
|
-
export { A as AuthUser, D as DEFAULT_MAX_AGE, a as DEFAULT_SALT, J as JwtPayload, M as MfJwtPayload, d as decodeSessionToken, e as encodeSessionToken, p as payloadToAuthUser, r as resolveTokenConfig } from './jwt-
|
|
1
|
+
import { R as RoleInfo, T as TokenConfig } from './jwt-EyXe_d9K.cjs';
|
|
2
|
+
export { A as AuthUser, D as DEFAULT_MAX_AGE, a as DEFAULT_SALT, J as JwtPayload, M as MfJwtPayload, d as decodeSessionToken, e as encodeSessionToken, p as payloadToAuthUser, r as resolveTokenConfig } from './jwt-EyXe_d9K.cjs';
|
|
3
3
|
|
|
4
4
|
/** Seconds. Impersonation token default: 1h (the normal session is 24h). */
|
|
5
5
|
declare const DEFAULT_IMPERSONATION_MAX_AGE: number;
|
|
@@ -91,4 +91,24 @@ declare function stampSessionTimes<T extends object>(token: T, now?: number): T
|
|
|
91
91
|
*/
|
|
92
92
|
declare function sessionState(token: SessionTimes, marks: SessionMarks): SessionState;
|
|
93
93
|
|
|
94
|
-
|
|
94
|
+
/**
|
|
95
|
+
* API key helpers for machine-to-machine calls. Isomorphic (Web Crypto, no
|
|
96
|
+
* `node:crypto`), so the core entry still loads in the browser and on the edge.
|
|
97
|
+
* The Nest guard that checks keys lives in '@telamonjs/auth/nest'.
|
|
98
|
+
*/
|
|
99
|
+
/**
|
|
100
|
+
* A new random API key: 32 bytes as URL-safe base64 (43 characters), after
|
|
101
|
+
* an optional `prefix` (e.g. `'svc_'`, so a leaked key is recognizable).
|
|
102
|
+
* Show it once; store it in an env var, or store `hashApiKey(key)` in the
|
|
103
|
+
* database.
|
|
104
|
+
*/
|
|
105
|
+
declare function generateApiKey(prefix?: string): string;
|
|
106
|
+
/**
|
|
107
|
+
* The hex sha256 of a key — what to store and look up instead of the key
|
|
108
|
+
* itself. Same digest as `createHash('sha256').update(key).digest('hex')`.
|
|
109
|
+
* A random 32-byte key needs no salt or slow hash: there is nothing to
|
|
110
|
+
* brute-force.
|
|
111
|
+
*/
|
|
112
|
+
declare function hashApiKey(key: string): Promise<string>;
|
|
113
|
+
|
|
114
|
+
export { type CreateImpersonationTokenInput, DEFAULT_IMPERSONATION_MAX_AGE, type ImpersonationParty, RoleInfo, type SessionMarks, type SessionState, type SessionTimes, TokenConfig, createImpersonationToken, generateApiKey, hashApiKey, sessionState, stampSessionTimes };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { R as RoleInfo, T as TokenConfig } from './jwt-
|
|
2
|
-
export { A as AuthUser, D as DEFAULT_MAX_AGE, a as DEFAULT_SALT, J as JwtPayload, M as MfJwtPayload, d as decodeSessionToken, e as encodeSessionToken, p as payloadToAuthUser, r as resolveTokenConfig } from './jwt-
|
|
1
|
+
import { R as RoleInfo, T as TokenConfig } from './jwt-EyXe_d9K.js';
|
|
2
|
+
export { A as AuthUser, D as DEFAULT_MAX_AGE, a as DEFAULT_SALT, J as JwtPayload, M as MfJwtPayload, d as decodeSessionToken, e as encodeSessionToken, p as payloadToAuthUser, r as resolveTokenConfig } from './jwt-EyXe_d9K.js';
|
|
3
3
|
|
|
4
4
|
/** Seconds. Impersonation token default: 1h (the normal session is 24h). */
|
|
5
5
|
declare const DEFAULT_IMPERSONATION_MAX_AGE: number;
|
|
@@ -91,4 +91,24 @@ declare function stampSessionTimes<T extends object>(token: T, now?: number): T
|
|
|
91
91
|
*/
|
|
92
92
|
declare function sessionState(token: SessionTimes, marks: SessionMarks): SessionState;
|
|
93
93
|
|
|
94
|
-
|
|
94
|
+
/**
|
|
95
|
+
* API key helpers for machine-to-machine calls. Isomorphic (Web Crypto, no
|
|
96
|
+
* `node:crypto`), so the core entry still loads in the browser and on the edge.
|
|
97
|
+
* The Nest guard that checks keys lives in '@telamonjs/auth/nest'.
|
|
98
|
+
*/
|
|
99
|
+
/**
|
|
100
|
+
* A new random API key: 32 bytes as URL-safe base64 (43 characters), after
|
|
101
|
+
* an optional `prefix` (e.g. `'svc_'`, so a leaked key is recognizable).
|
|
102
|
+
* Show it once; store it in an env var, or store `hashApiKey(key)` in the
|
|
103
|
+
* database.
|
|
104
|
+
*/
|
|
105
|
+
declare function generateApiKey(prefix?: string): string;
|
|
106
|
+
/**
|
|
107
|
+
* The hex sha256 of a key — what to store and look up instead of the key
|
|
108
|
+
* itself. Same digest as `createHash('sha256').update(key).digest('hex')`.
|
|
109
|
+
* A random 32-byte key needs no salt or slow hash: there is nothing to
|
|
110
|
+
* brute-force.
|
|
111
|
+
*/
|
|
112
|
+
declare function hashApiKey(key: string): Promise<string>;
|
|
113
|
+
|
|
114
|
+
export { type CreateImpersonationTokenInput, DEFAULT_IMPERSONATION_MAX_AGE, type ImpersonationParty, RoleInfo, type SessionMarks, type SessionState, type SessionTimes, TokenConfig, createImpersonationToken, generateApiKey, hashApiKey, sessionState, stampSessionTimes };
|
package/dist/index.js
CHANGED
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
resolveTokenConfig,
|
|
8
8
|
sessionState,
|
|
9
9
|
stampSessionTimes
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-G73ASFMN.js";
|
|
11
11
|
|
|
12
12
|
// src/impersonation.ts
|
|
13
13
|
var DEFAULT_IMPERSONATION_MAX_AGE = 60 * 60;
|
|
@@ -43,6 +43,23 @@ async function createImpersonationToken({
|
|
|
43
43
|
maxAge: maxAge ?? config?.maxAge ?? DEFAULT_IMPERSONATION_MAX_AGE
|
|
44
44
|
});
|
|
45
45
|
}
|
|
46
|
+
|
|
47
|
+
// src/api-key.ts
|
|
48
|
+
function generateApiKey(prefix = "") {
|
|
49
|
+
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(32));
|
|
50
|
+
const base64 = btoa(String.fromCharCode(...bytes));
|
|
51
|
+
return prefix + base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
52
|
+
}
|
|
53
|
+
async function hashApiKey(key) {
|
|
54
|
+
const digest = await globalThis.crypto.subtle.digest(
|
|
55
|
+
"SHA-256",
|
|
56
|
+
new TextEncoder().encode(key)
|
|
57
|
+
);
|
|
58
|
+
return Array.from(
|
|
59
|
+
new Uint8Array(digest),
|
|
60
|
+
(b) => b.toString(16).padStart(2, "0")
|
|
61
|
+
).join("");
|
|
62
|
+
}
|
|
46
63
|
export {
|
|
47
64
|
DEFAULT_IMPERSONATION_MAX_AGE,
|
|
48
65
|
DEFAULT_MAX_AGE,
|
|
@@ -50,6 +67,8 @@ export {
|
|
|
50
67
|
createImpersonationToken,
|
|
51
68
|
decodeSessionToken,
|
|
52
69
|
encodeSessionToken,
|
|
70
|
+
generateApiKey,
|
|
71
|
+
hashApiKey,
|
|
53
72
|
payloadToAuthUser,
|
|
54
73
|
resolveTokenConfig,
|
|
55
74
|
sessionState,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/impersonation.ts"],"sourcesContent":["import { encodeSessionToken, type TokenConfig } from './jwt'\nimport type { MfJwtPayload, RoleInfo } from './types'\n\n/** Seconds. Impersonation token default: 1h (the normal session is 24h). */\nexport const DEFAULT_IMPERSONATION_MAX_AGE = 60 * 60\n\n/**\n * Data for one side of the impersonation, ALREADY RESOLVED by the app.\n * The package never touches the database — loading the user/roles/permissions\n * is the app's job.\n */\nexport interface ImpersonationParty {\n id: string\n pessoaId?: string\n name?: string\n email: string\n role: RoleInfo\n roles?: RoleInfo[]\n permissions?: string[]\n}\n\nexport interface CreateImpersonationTokenInput {\n /** User being impersonated — becomes the subject of the token. */\n target: ImpersonationParty & { permissions: string[] }\n /** Admin who started it (becomes the `original*` block). */\n actor: ImpersonationParty\n /** Id of the app's audit record (used by the revocation check in the guard). */\n logId: string\n /** Seconds. Default: `DEFAULT_IMPERSONATION_MAX_AGE` (1h). */\n maxAge?: number\n /**\n * Includes `originalPermissions` in the token. Default: false — it only\n * bloats the payload (chunked cookie) and nothing in the package reads\n * those permissions.\n */\n includeOriginalPermissions?: boolean\n}\n\n/**\n * Issues the impersonation token: a session JWE whose SUBJECT is the target\n * and which carries the actor in the `original*` claims — exactly the shape\n * `payloadToAuthUser` reads back (`isImpersonating` + `originalUser`).\n *\n * The token doubles as a credential: sent as `Authorization: Bearer` it\n * authenticates as the target on the API, with `impersonationLogId` for\n * revocation.\n *\n * ```ts\n * const token = await createImpersonationToken({ target, actor, logId: log.id })\n * ```\n *\n * `iat`/`exp`/`jti` are written by `@auth/core/jwt.encode` — the TTL goes\n * through `maxAge`, never as a claim in the payload.\n */\nexport async function createImpersonationToken(\n {\n target,\n actor,\n logId,\n maxAge,\n includeOriginalPermissions,\n }: CreateImpersonationTokenInput,\n config?: TokenConfig\n): Promise<string> {\n const payload: MfJwtPayload = {\n sub: target.id,\n id: target.id,\n pessoaId: target.pessoaId,\n name: target.name,\n email: target.email,\n role: target.role,\n roles: target.roles ?? [target.role],\n permissions: target.permissions ?? [],\n\n impersonatedUserId: target.id,\n impersonationLogId: logId,\n originalUserId: actor.id,\n originalUserName: actor.name,\n originalUserEmail: actor.email,\n originalUserRole: actor.role,\n originalUserRoles: actor.roles ?? [actor.role],\n }\n\n if (includeOriginalPermissions) {\n payload.originalPermissions = actor.permissions ?? []\n }\n\n return encodeSessionToken(payload, {\n ...config,\n maxAge: maxAge ?? config?.maxAge ?? DEFAULT_IMPERSONATION_MAX_AGE,\n })\n}\n"],"mappings":";;;;;;;;;;;;AAIO,IAAM,gCAAgC,KAAK;AAkDlD,eAAsB,yBACpB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GACA,QACiB;AACjB,QAAM,UAAwB;AAAA,IAC5B,KAAK,OAAO;AAAA,IACZ,IAAI,OAAO;AAAA,IACX,UAAU,OAAO;AAAA,IACjB,MAAM,OAAO;AAAA,IACb,OAAO,OAAO;AAAA,IACd,MAAM,OAAO;AAAA,IACb,OAAO,OAAO,SAAS,CAAC,OAAO,IAAI;AAAA,IACnC,aAAa,OAAO,eAAe,CAAC;AAAA,IAEpC,oBAAoB,OAAO;AAAA,IAC3B,oBAAoB;AAAA,IACpB,gBAAgB,MAAM;AAAA,IACtB,kBAAkB,MAAM;AAAA,IACxB,mBAAmB,MAAM;AAAA,IACzB,kBAAkB,MAAM;AAAA,IACxB,mBAAmB,MAAM,SAAS,CAAC,MAAM,IAAI;AAAA,EAC/C;AAEA,MAAI,4BAA4B;AAC9B,YAAQ,sBAAsB,MAAM,eAAe,CAAC;AAAA,EACtD;AAEA,SAAO,mBAAmB,SAAS;AAAA,IACjC,GAAG;AAAA,IACH,QAAQ,UAAU,QAAQ,UAAU;AAAA,EACtC,CAAC;AACH;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/impersonation.ts","../src/api-key.ts"],"sourcesContent":["import { encodeSessionToken, type TokenConfig } from './jwt'\nimport type { MfJwtPayload, RoleInfo } from './types'\n\n/** Seconds. Impersonation token default: 1h (the normal session is 24h). */\nexport const DEFAULT_IMPERSONATION_MAX_AGE = 60 * 60\n\n/**\n * Data for one side of the impersonation, ALREADY RESOLVED by the app.\n * The package never touches the database — loading the user/roles/permissions\n * is the app's job.\n */\nexport interface ImpersonationParty {\n id: string\n pessoaId?: string\n name?: string\n email: string\n role: RoleInfo\n roles?: RoleInfo[]\n permissions?: string[]\n}\n\nexport interface CreateImpersonationTokenInput {\n /** User being impersonated — becomes the subject of the token. */\n target: ImpersonationParty & { permissions: string[] }\n /** Admin who started it (becomes the `original*` block). */\n actor: ImpersonationParty\n /** Id of the app's audit record (used by the revocation check in the guard). */\n logId: string\n /** Seconds. Default: `DEFAULT_IMPERSONATION_MAX_AGE` (1h). */\n maxAge?: number\n /**\n * Includes `originalPermissions` in the token. Default: false — it only\n * bloats the payload (chunked cookie) and nothing in the package reads\n * those permissions.\n */\n includeOriginalPermissions?: boolean\n}\n\n/**\n * Issues the impersonation token: a session JWE whose SUBJECT is the target\n * and which carries the actor in the `original*` claims — exactly the shape\n * `payloadToAuthUser` reads back (`isImpersonating` + `originalUser`).\n *\n * The token doubles as a credential: sent as `Authorization: Bearer` it\n * authenticates as the target on the API, with `impersonationLogId` for\n * revocation.\n *\n * ```ts\n * const token = await createImpersonationToken({ target, actor, logId: log.id })\n * ```\n *\n * `iat`/`exp`/`jti` are written by `@auth/core/jwt.encode` — the TTL goes\n * through `maxAge`, never as a claim in the payload.\n */\nexport async function createImpersonationToken(\n {\n target,\n actor,\n logId,\n maxAge,\n includeOriginalPermissions,\n }: CreateImpersonationTokenInput,\n config?: TokenConfig\n): Promise<string> {\n const payload: MfJwtPayload = {\n sub: target.id,\n id: target.id,\n pessoaId: target.pessoaId,\n name: target.name,\n email: target.email,\n role: target.role,\n roles: target.roles ?? [target.role],\n permissions: target.permissions ?? [],\n\n impersonatedUserId: target.id,\n impersonationLogId: logId,\n originalUserId: actor.id,\n originalUserName: actor.name,\n originalUserEmail: actor.email,\n originalUserRole: actor.role,\n originalUserRoles: actor.roles ?? [actor.role],\n }\n\n if (includeOriginalPermissions) {\n payload.originalPermissions = actor.permissions ?? []\n }\n\n return encodeSessionToken(payload, {\n ...config,\n maxAge: maxAge ?? config?.maxAge ?? DEFAULT_IMPERSONATION_MAX_AGE,\n })\n}\n","/**\n * API key helpers for machine-to-machine calls. Isomorphic (Web Crypto, no\n * `node:crypto`), so the core entry still loads in the browser and on the edge.\n * The Nest guard that checks keys lives in '@telamonjs/auth/nest'.\n */\n\n/**\n * A new random API key: 32 bytes as URL-safe base64 (43 characters), after\n * an optional `prefix` (e.g. `'svc_'`, so a leaked key is recognizable).\n * Show it once; store it in an env var, or store `hashApiKey(key)` in the\n * database.\n */\nexport function generateApiKey(prefix = ''): string {\n const bytes = globalThis.crypto.getRandomValues(new Uint8Array(32))\n const base64 = btoa(String.fromCharCode(...bytes))\n return (\n prefix +\n base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n )\n}\n\n/**\n * The hex sha256 of a key — what to store and look up instead of the key\n * itself. Same digest as `createHash('sha256').update(key).digest('hex')`.\n * A random 32-byte key needs no salt or slow hash: there is nothing to\n * brute-force.\n */\nexport async function hashApiKey(key: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(key)\n )\n return Array.from(new Uint8Array(digest), b =>\n b.toString(16).padStart(2, '0')\n ).join('')\n}\n"],"mappings":";;;;;;;;;;;;AAIO,IAAM,gCAAgC,KAAK;AAkDlD,eAAsB,yBACpB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GACA,QACiB;AACjB,QAAM,UAAwB;AAAA,IAC5B,KAAK,OAAO;AAAA,IACZ,IAAI,OAAO;AAAA,IACX,UAAU,OAAO;AAAA,IACjB,MAAM,OAAO;AAAA,IACb,OAAO,OAAO;AAAA,IACd,MAAM,OAAO;AAAA,IACb,OAAO,OAAO,SAAS,CAAC,OAAO,IAAI;AAAA,IACnC,aAAa,OAAO,eAAe,CAAC;AAAA,IAEpC,oBAAoB,OAAO;AAAA,IAC3B,oBAAoB;AAAA,IACpB,gBAAgB,MAAM;AAAA,IACtB,kBAAkB,MAAM;AAAA,IACxB,mBAAmB,MAAM;AAAA,IACzB,kBAAkB,MAAM;AAAA,IACxB,mBAAmB,MAAM,SAAS,CAAC,MAAM,IAAI;AAAA,EAC/C;AAEA,MAAI,4BAA4B;AAC9B,YAAQ,sBAAsB,MAAM,eAAe,CAAC;AAAA,EACtD;AAEA,SAAO,mBAAmB,SAAS;AAAA,IACjC,GAAG;AAAA,IACH,QAAQ,UAAU,QAAQ,UAAU;AAAA,EACtC,CAAC;AACH;;;AC/EO,SAAS,eAAe,SAAS,IAAY;AAClD,QAAM,QAAQ,WAAW,OAAO,gBAAgB,IAAI,WAAW,EAAE,CAAC;AAClE,QAAM,SAAS,KAAK,OAAO,aAAa,GAAG,KAAK,CAAC;AACjD,SACE,SACA,OAAO,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,EAAE;AAEpE;AAQA,eAAsB,WAAW,KAA8B;AAC7D,QAAM,SAAS,MAAM,WAAW,OAAO,OAAO;AAAA,IAC5C;AAAA,IACA,IAAI,YAAY,EAAE,OAAO,GAAG;AAAA,EAC9B;AACA,SAAO,MAAM;AAAA,IAAK,IAAI,WAAW,MAAM;AAAA,IAAG,OACxC,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AAAA,EAChC,EAAE,KAAK,EAAE;AACX;","names":[]}
|
|
@@ -75,7 +75,11 @@ interface TokenConfig {
|
|
|
75
75
|
* v4 cookie use 'next-auth.session-token'.
|
|
76
76
|
*/
|
|
77
77
|
salt?: string;
|
|
78
|
-
/**
|
|
78
|
+
/**
|
|
79
|
+
* Seconds. Encoding: the token lifetime, default 24h. Decoding (and the
|
|
80
|
+
* guard): only when set, rejects a token issued longer ago than this;
|
|
81
|
+
* unset, the token's own `exp` is the only limit.
|
|
82
|
+
*/
|
|
79
83
|
maxAge?: number;
|
|
80
84
|
}
|
|
81
85
|
declare const DEFAULT_SALT = "authjs.session-token";
|
|
@@ -89,7 +93,11 @@ declare function resolveTokenConfig(config?: TokenConfig): Required<TokenConfig>
|
|
|
89
93
|
* stamped (on a copy), so `sessionState` does not read it as issued at 0.
|
|
90
94
|
*/
|
|
91
95
|
declare function encodeSessionToken(payload: MfJwtPayload, config?: TokenConfig): Promise<string>;
|
|
92
|
-
/**
|
|
96
|
+
/**
|
|
97
|
+
* Decodes the session JWE. Returns null for an invalid/expired token.
|
|
98
|
+
* An explicit `config.maxAge` also rejects a token issued (`iat`) more than
|
|
99
|
+
* that many seconds ago; without it, only the token's own `exp` applies.
|
|
100
|
+
*/
|
|
93
101
|
declare function decodeSessionToken(token: string, config?: TokenConfig): Promise<MfJwtPayload | null>;
|
|
94
102
|
/**
|
|
95
103
|
* Maps the JWT payload to the request's AuthUser,
|
|
@@ -75,7 +75,11 @@ interface TokenConfig {
|
|
|
75
75
|
* v4 cookie use 'next-auth.session-token'.
|
|
76
76
|
*/
|
|
77
77
|
salt?: string;
|
|
78
|
-
/**
|
|
78
|
+
/**
|
|
79
|
+
* Seconds. Encoding: the token lifetime, default 24h. Decoding (and the
|
|
80
|
+
* guard): only when set, rejects a token issued longer ago than this;
|
|
81
|
+
* unset, the token's own `exp` is the only limit.
|
|
82
|
+
*/
|
|
79
83
|
maxAge?: number;
|
|
80
84
|
}
|
|
81
85
|
declare const DEFAULT_SALT = "authjs.session-token";
|
|
@@ -89,7 +93,11 @@ declare function resolveTokenConfig(config?: TokenConfig): Required<TokenConfig>
|
|
|
89
93
|
* stamped (on a copy), so `sessionState` does not read it as issued at 0.
|
|
90
94
|
*/
|
|
91
95
|
declare function encodeSessionToken(payload: MfJwtPayload, config?: TokenConfig): Promise<string>;
|
|
92
|
-
/**
|
|
96
|
+
/**
|
|
97
|
+
* Decodes the session JWE. Returns null for an invalid/expired token.
|
|
98
|
+
* An explicit `config.maxAge` also rejects a token issued (`iat`) more than
|
|
99
|
+
* that many seconds ago; without it, only the token's own `exp` applies.
|
|
100
|
+
*/
|
|
93
101
|
declare function decodeSessionToken(token: string, config?: TokenConfig): Promise<MfJwtPayload | null>;
|
|
94
102
|
/**
|
|
95
103
|
* Maps the JWT payload to the request's AuthUser,
|
package/dist/nest/index.cjs
CHANGED
|
@@ -28,15 +28,19 @@ var __decorateClass = (decorators, target, key, kind) => {
|
|
|
28
28
|
// src/nest/index.ts
|
|
29
29
|
var nest_exports = {};
|
|
30
30
|
__export(nest_exports, {
|
|
31
|
+
ALLOW_SERVICE_TOKEN_KEY: () => ALLOW_SERVICE_TOKEN_KEY,
|
|
32
|
+
AllowServiceToken: () => AllowServiceToken,
|
|
31
33
|
IS_PUBLIC_KEY: () => IS_PUBLIC_KEY,
|
|
32
34
|
JwtAuthGuardBase: () => JwtAuthGuardBase,
|
|
33
35
|
Public: () => Public,
|
|
34
|
-
|
|
36
|
+
createApiKeyGuard: () => createApiKeyGuard,
|
|
37
|
+
createJwtAuthGuard: () => createJwtAuthGuard,
|
|
38
|
+
staticApiKey: () => staticApiKey
|
|
35
39
|
});
|
|
36
40
|
module.exports = __toCommonJS(nest_exports);
|
|
37
41
|
|
|
38
42
|
// src/nest/jwt-auth.guard.ts
|
|
39
|
-
var
|
|
43
|
+
var import_common4 = require("@nestjs/common");
|
|
40
44
|
var import_core = require("@nestjs/core");
|
|
41
45
|
|
|
42
46
|
// src/jwt.ts
|
|
@@ -58,7 +62,11 @@ async function decodeSessionToken(token, config) {
|
|
|
58
62
|
const { secret, salt } = resolveTokenConfig(config);
|
|
59
63
|
try {
|
|
60
64
|
const payload = await (0, import_jwt.decode)({ token, secret, salt });
|
|
61
|
-
|
|
65
|
+
if (!payload) return null;
|
|
66
|
+
if (config?.maxAge != null && (payload.iat ?? 0) + config.maxAge < Date.now() / 1e3) {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
return payload;
|
|
62
70
|
} catch {
|
|
63
71
|
return null;
|
|
64
72
|
}
|
|
@@ -100,6 +108,53 @@ var import_common = require("@nestjs/common");
|
|
|
100
108
|
var IS_PUBLIC_KEY = "isPublic";
|
|
101
109
|
var Public = () => (0, import_common.SetMetadata)(IS_PUBLIC_KEY, true);
|
|
102
110
|
|
|
111
|
+
// src/nest/allow-service-token.decorator.ts
|
|
112
|
+
var import_common2 = require("@nestjs/common");
|
|
113
|
+
var ALLOW_SERVICE_TOKEN_KEY = "allowServiceToken";
|
|
114
|
+
var AllowServiceToken = () => (0, import_common2.SetMetadata)(ALLOW_SERVICE_TOKEN_KEY, true);
|
|
115
|
+
|
|
116
|
+
// src/nest/api-key.guard.ts
|
|
117
|
+
var import_node_crypto = require("crypto");
|
|
118
|
+
var import_common3 = require("@nestjs/common");
|
|
119
|
+
var INVALID_KEY = "Invalid or missing API key";
|
|
120
|
+
async function verifyApiKey(request, options) {
|
|
121
|
+
const header = options.header ?? "x-api-key";
|
|
122
|
+
let key = header ? request.headers[header.toLowerCase()] : void 0;
|
|
123
|
+
if (!key && options.bearer) {
|
|
124
|
+
const auth = request.headers["authorization"];
|
|
125
|
+
if (typeof auth === "string" && auth.startsWith("Bearer ")) {
|
|
126
|
+
key = auth.slice(7).trim();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (typeof key !== "string" || !key) return null;
|
|
130
|
+
return await options.verify(key, request) || null;
|
|
131
|
+
}
|
|
132
|
+
function createApiKeyGuard(options) {
|
|
133
|
+
let ApiKeyGuard = class {
|
|
134
|
+
async canActivate(context) {
|
|
135
|
+
const request = context.switchToHttp().getRequest();
|
|
136
|
+
const principal = await verifyApiKey(request, options);
|
|
137
|
+
if (principal == null) {
|
|
138
|
+
throw options.createException?.(401, INVALID_KEY) ?? new import_common3.UnauthorizedException(INVALID_KEY);
|
|
139
|
+
}
|
|
140
|
+
request.servicePrincipal = principal;
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
ApiKeyGuard = __decorateClass([
|
|
145
|
+
(0, import_common3.Injectable)()
|
|
146
|
+
], ApiKeyGuard);
|
|
147
|
+
return ApiKeyGuard;
|
|
148
|
+
}
|
|
149
|
+
var sha256 = (value) => (0, import_node_crypto.createHash)("sha256").update(value).digest();
|
|
150
|
+
function staticApiKey(expected, name = "service") {
|
|
151
|
+
return (key) => {
|
|
152
|
+
const value = typeof expected === "function" ? expected() : expected;
|
|
153
|
+
if (!value || !key) return null;
|
|
154
|
+
return (0, import_node_crypto.timingSafeEqual)(sha256(key), sha256(value)) ? { name } : null;
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
103
158
|
// src/nest/jwt-auth.guard.ts
|
|
104
159
|
var VALIDATE_CACHE_MAX = 1e3;
|
|
105
160
|
var JwtAuthGuardBase = class {
|
|
@@ -145,11 +200,11 @@ var JwtAuthGuardBase = class {
|
|
|
145
200
|
};
|
|
146
201
|
function createJwtAuthGuard(options) {
|
|
147
202
|
const salt = options?.salt ?? DEFAULT_SALT;
|
|
148
|
-
const cookieNames = options?.cookieNames ?? [
|
|
203
|
+
const cookieNames = options?.cookieNames ?? [`__Secure-${salt}`, salt];
|
|
149
204
|
const headerSalts = [.../* @__PURE__ */ new Set([salt, ...cookieNames])];
|
|
150
|
-
const unauthorized = (message) => options?.createException?.(401, message) ?? new
|
|
205
|
+
const unauthorized = (message) => options?.createException?.(401, message) ?? new import_common4.UnauthorizedException(message);
|
|
151
206
|
let warnedIrrevocable = false;
|
|
152
|
-
const logger = new
|
|
207
|
+
const logger = new import_common4.Logger("JwtAuthGuard");
|
|
153
208
|
const cacheTtl = options?.validateUserCacheTtlMs ?? 0;
|
|
154
209
|
const verdicts = /* @__PURE__ */ new Map();
|
|
155
210
|
let JwtAuthGuard = class extends JwtAuthGuardBase {
|
|
@@ -166,12 +221,23 @@ function createJwtAuthGuard(options) {
|
|
|
166
221
|
);
|
|
167
222
|
if (isPublic) return true;
|
|
168
223
|
const request = context.switchToHttp().getRequest();
|
|
224
|
+
if (options?.apiKey && this.reflector.getAllAndOverride(ALLOW_SERVICE_TOKEN_KEY, [
|
|
225
|
+
context.getHandler(),
|
|
226
|
+
context.getClass()
|
|
227
|
+
])) {
|
|
228
|
+
const principal = await verifyApiKey(request, options.apiKey);
|
|
229
|
+
if (principal != null) {
|
|
230
|
+
request.servicePrincipal = principal;
|
|
231
|
+
return true;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
169
234
|
const secret = typeof options?.secret === "function" ? await options.secret() : options?.secret;
|
|
170
235
|
for (const candidate of this.extractTokenCandidates(request)) {
|
|
171
236
|
for (const candidateSalt of candidate.salts) {
|
|
172
237
|
const payload = await decodeSessionToken(candidate.token, {
|
|
173
238
|
secret,
|
|
174
|
-
salt: candidateSalt
|
|
239
|
+
salt: candidateSalt,
|
|
240
|
+
maxAge: options?.maxAge
|
|
175
241
|
});
|
|
176
242
|
if (payload) {
|
|
177
243
|
if (payload.impersonatedUserId && options?.isImpersonationActive) {
|
|
@@ -236,6 +302,10 @@ function createJwtAuthGuard(options) {
|
|
|
236
302
|
candidates.push({ token: queryToken, salts: headerSalts });
|
|
237
303
|
}
|
|
238
304
|
for (const name of cookieNames) {
|
|
305
|
+
const secureTwin = `__Secure-${name}`;
|
|
306
|
+
if (cookieNames.includes(secureTwin) && this.readCookie(request, secureTwin)) {
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
239
309
|
const token = this.readCookie(request, name);
|
|
240
310
|
if (token) {
|
|
241
311
|
candidates.push({ token, salts: [.../* @__PURE__ */ new Set([name, salt])] });
|
|
@@ -258,15 +328,19 @@ function createJwtAuthGuard(options) {
|
|
|
258
328
|
}
|
|
259
329
|
};
|
|
260
330
|
JwtAuthGuard = __decorateClass([
|
|
261
|
-
(0,
|
|
331
|
+
(0, import_common4.Injectable)()
|
|
262
332
|
], JwtAuthGuard);
|
|
263
333
|
return JwtAuthGuard;
|
|
264
334
|
}
|
|
265
335
|
// Annotate the CommonJS export names for ESM import in node:
|
|
266
336
|
0 && (module.exports = {
|
|
337
|
+
ALLOW_SERVICE_TOKEN_KEY,
|
|
338
|
+
AllowServiceToken,
|
|
267
339
|
IS_PUBLIC_KEY,
|
|
268
340
|
JwtAuthGuardBase,
|
|
269
341
|
Public,
|
|
270
|
-
|
|
342
|
+
createApiKeyGuard,
|
|
343
|
+
createJwtAuthGuard,
|
|
344
|
+
staticApiKey
|
|
271
345
|
});
|
|
272
346
|
//# sourceMappingURL=index.cjs.map
|