@feasibleone/blong-login 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,227 @@
1
+ import crypto from 'node:crypto';
2
+
3
+ import {library} from '@feasibleone/blong';
4
+
5
+ /** Default restore-cookie name (override via `login.session.cookieName`). */
6
+ export const SESSION_COOKIE_DEFAULT = 'blong.session';
7
+
8
+ /**
9
+ * Default path-scope for the restore cookie — it is only sent to the restore
10
+ * endpoint, so a captured cookie cannot be used against other URLs.
11
+ * Override via `login.session.cookiePath`.
12
+ */
13
+ export const SESSION_COOKIE_PATH_DEFAULT = '/rpc/login/token/restore';
14
+
15
+ /** SHA-256 hex digest — used for refresh-token and cookie-handle hashing. */
16
+ function sha256Hex(value: string): string {
17
+ return crypto.createHash('sha256').update(value).digest('hex');
18
+ }
19
+
20
+ /** A fresh opaque cookie handle (128 bits of entropy, base64url). */
21
+ function newCookieHandle(): string {
22
+ return crypto.randomBytes(16).toString('base64url');
23
+ }
24
+
25
+ /** Format a BINARY(16) Buffer as a dashed UUID string. */
26
+ function bufToUuid(buf: Buffer): string {
27
+ const hex = buf.toString('hex');
28
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
29
+ }
30
+
31
+ /** Base64 (wire) binary key → dashed UUID string. */
32
+ function base64ToUuid(value: string): string {
33
+ return bufToUuid(Buffer.from(value, 'base64'));
34
+ }
35
+
36
+ /** The token response shape returned by `login.token.*` endpoints. */
37
+ export interface ITokenResult {
38
+ access_token: string;
39
+ expires_in: number;
40
+ refresh_token: string;
41
+ refresh_token_expires_in: number;
42
+ session_id: string;
43
+ permissions: string[] | boolean;
44
+ /**
45
+ * Resolved from the user's profile during login (best-effort). Carries the
46
+ * actor id and the preferred language so the UI can apply the user's locale
47
+ * immediately after login — absent when no profile handler is configured.
48
+ */
49
+ profile?: {actorId?: string; language?: string};
50
+ }
51
+
52
+ /**
53
+ * Access-realm methods that `blong-login` calls, made **configurable** so the
54
+ * realm can run without blong-access (lightweight suites). Each entry is a
55
+ * wire name (default: the blong-access handler) or `false` to disable that
56
+ * functionality.
57
+ */
58
+ export type LoginMethodKey =
59
+ | 'credentialCheck'
60
+ | 'credentialCheckClient'
61
+ | 'identityCheck'
62
+ | 'permissionList'
63
+ | 'profileGet'
64
+ | 'sessionCreate'
65
+ | 'sessionVerify'
66
+ | 'sessionRestore'
67
+ | 'sessionRotate'
68
+ | 'sessionClose'
69
+ | 'sessionCleanup'
70
+ | 'auditRecord';
71
+
72
+ export type LoginMethods = Partial<Record<LoginMethodKey, string | false>>;
73
+
74
+ /** Default wire names — the blong-access handlers. */
75
+ export const LOGIN_METHOD_DEFAULTS: Record<LoginMethodKey, string> = {
76
+ credentialCheck: 'access.credential.check',
77
+ credentialCheckClient: 'access.credential.checkClient',
78
+ identityCheck: 'access.identity.check',
79
+ permissionList: 'access.permission.list',
80
+ profileGet: 'access.profile.get',
81
+ sessionCreate: 'access.session.create',
82
+ sessionVerify: 'access.session.verify',
83
+ sessionRestore: 'access.session.restore',
84
+ sessionRotate: 'access.session.rotate',
85
+ sessionClose: 'access.session.close',
86
+ sessionCleanup: 'access.session.cleanup',
87
+ auditRecord: 'access.audit.record',
88
+ };
89
+
90
+ /**
91
+ * Resolve one configured login method against the handler proxy — the
92
+ * `login.methods.*` override wins, otherwise the blong-access default applies.
93
+ * Returns `undefined` when the method is explicitly disabled (`false`); the
94
+ * caller then skips that functionality. Throws when the configured name does
95
+ * not resolve to a registered handler (a typo must not silently disable it).
96
+ */
97
+ export function resolveLoginMethod(
98
+ config: {methods?: LoginMethods},
99
+ key: LoginMethodKey,
100
+ handler: Record<string, unknown>,
101
+ ): ((...args: unknown[]) => unknown) | undefined {
102
+ const name = config.methods?.[key] ?? LOGIN_METHOD_DEFAULTS[key];
103
+ if (!name) return undefined;
104
+ const fn = (handler as Record<string, unknown>)[name];
105
+ if (typeof fn !== 'function') {
106
+ throw new Error(
107
+ `login.methods.${key} refers to unknown method '${name}' — configure a handler or set it to false`,
108
+ );
109
+ }
110
+ return fn as (...args: unknown[]) => unknown;
111
+ }
112
+
113
+ /** A single resolved (bound) login method — `undefined` when disabled. */
114
+ export type ResolvedLoginMethod = ((...args: unknown[]) => unknown) | undefined;
115
+
116
+ /** All access-methods resolved once by the `sessionLib` library factory. */
117
+ export interface ResolvedLoginMethods {
118
+ credentialCheck?: ResolvedLoginMethod;
119
+ credentialCheckClient?: ResolvedLoginMethod;
120
+ identityCheck?: ResolvedLoginMethod;
121
+ permissionList?: ResolvedLoginMethod;
122
+ profileGet?: ResolvedLoginMethod;
123
+ sessionCreate?: ResolvedLoginMethod;
124
+ sessionVerify?: ResolvedLoginMethod;
125
+ sessionRestore?: ResolvedLoginMethod;
126
+ sessionRotate?: ResolvedLoginMethod;
127
+ sessionClose?: ResolvedLoginMethod;
128
+ sessionCleanup?: ResolvedLoginMethod;
129
+ auditRecord?: ResolvedLoginMethod;
130
+ }
131
+
132
+ /** Session-relevant `login` config consumed by the `sessionLib` library. */
133
+ export interface SessionConfig {
134
+ methods?: LoginMethods;
135
+ expire?: {cookie?: number; inactivity?: number; deleteAfter?: number};
136
+ session?: {
137
+ cookieName?: string;
138
+ cookiePath?: string;
139
+ isSecure?: boolean;
140
+ isHttpOnly?: boolean;
141
+ };
142
+ }
143
+
144
+ /** Cookie options for the restore cookie. */
145
+ export type SessionCookieOptions = {
146
+ ttl: number;
147
+ isSecure: boolean;
148
+ isHttpOnly: boolean;
149
+ isSameSite: 'lax';
150
+ path: string;
151
+ };
152
+
153
+ /**
154
+ * Cookie options for the restore cookie, computed from config — a suite can
155
+ * override the defaults via `login.session.*` / `login.expire.cookie`.
156
+ */
157
+ function sessionCookieOptions(config: SessionConfig): SessionCookieOptions {
158
+ return {
159
+ ttl: (config.expire?.cookie ?? 8 * 60 * 60) * 1000,
160
+ isSecure: config.session?.isSecure ?? true,
161
+ isHttpOnly: config.session?.isHttpOnly ?? true,
162
+ isSameSite: 'lax',
163
+ path: config.session?.cookiePath ?? SESSION_COOKIE_PATH_DEFAULT,
164
+ };
165
+ }
166
+
167
+ /**
168
+ * The params a login caller passes to `access.session.cleanup`.
169
+ *
170
+ * `login.expire.deleteAfter` is the documented knob, but the access handler
171
+ * falls back to its own 24-hour constant when it is absent — so a suite that
172
+ * configures the value would see it have no effect (T-165). Passing the
173
+ * configured number through, and nothing when it is unset, keeps the two in
174
+ * step.
175
+ */
176
+ export function sessionCleanupParams(config: SessionConfig): {deleteAfter?: number} {
177
+ const deleteAfter = config.expire?.deleteAfter;
178
+ return deleteAfter === undefined ? {} : {deleteAfter};
179
+ }
180
+
181
+ /** Read the restore cookie value from `$meta.httpRequest.state` (cookies). */
182
+ function readSessionCookie($meta: unknown, cookieName: string): string | undefined {
183
+ const httpRequest = ($meta as {httpRequest?: {state?: Record<string, string>}})?.httpRequest;
184
+ return httpRequest?.state?.[cookieName];
185
+ }
186
+
187
+ /**
188
+ * `sessionLib` — the login group's configurable-bindings library (see the
189
+ * blong-handler skill → "Library as a configurable-bindings bundle").
190
+ *
191
+ * The factory runs ONCE at layer assembly and resolves every configurable
192
+ * access-realm method against the `handler` proxy into the conventional
193
+ * `methods` map — soft dependencies a suite can override or disable via
194
+ * `login.methods.*`. The rest are pure helpers (cookie-options construction,
195
+ * hashing, cookie reading). Cookie/session CONSTANTS are deliberately NOT
196
+ * re-exported here — handlers read them straight from `config`.
197
+ *
198
+ * const {methods, sha256Hex, sessionCookieOptions} = lib;
199
+ * methods.auditRecord?.({...}, $meta);
200
+ * const hash = sha256Hex<string>(refreshToken);
201
+ */
202
+ export default library(({config, handler}) => {
203
+ const methods: ResolvedLoginMethods = {
204
+ credentialCheck: resolveLoginMethod(config, 'credentialCheck', handler),
205
+ credentialCheckClient: resolveLoginMethod(config, 'credentialCheckClient', handler),
206
+ identityCheck: resolveLoginMethod(config, 'identityCheck', handler),
207
+ permissionList: resolveLoginMethod(config, 'permissionList', handler),
208
+ profileGet: resolveLoginMethod(config, 'profileGet', handler),
209
+ sessionCreate: resolveLoginMethod(config, 'sessionCreate', handler),
210
+ sessionVerify: resolveLoginMethod(config, 'sessionVerify', handler),
211
+ sessionRestore: resolveLoginMethod(config, 'sessionRestore', handler),
212
+ sessionRotate: resolveLoginMethod(config, 'sessionRotate', handler),
213
+ sessionClose: resolveLoginMethod(config, 'sessionClose', handler),
214
+ sessionCleanup: resolveLoginMethod(config, 'sessionCleanup', handler),
215
+ auditRecord: resolveLoginMethod(config, 'auditRecord', handler),
216
+ };
217
+ return {
218
+ /** Conventional map of resolved access-method bindings. */
219
+ methods,
220
+ sha256Hex,
221
+ newCookieHandle,
222
+ sessionCookieOptions,
223
+ readSessionCookie,
224
+ bufToUuid,
225
+ base64ToUuid,
226
+ };
227
+ });
@@ -0,0 +1,112 @@
1
+ import {library} from '@feasibleone/blong';
2
+ import {SignJWT, calculateJwkThumbprint, createLocalJWKSet, importJWK, type JWK} from 'jose';
3
+
4
+ /** The private members of a JWK: RSA's primes, EC's scalar, an octet key and its other primes. */
5
+ const PRIVATE_JWK_MEMBERS = ['d', 'p', 'q', 'dp', 'dq', 'qi', 'k', 'oth'];
6
+
7
+ /**
8
+ * The public half of a JWK: what a client verifies the server with and encrypts to, and all it may
9
+ * have. The value published here is `gateway.public`, which `mle.ts` fills with `mle.keys` — public
10
+ * JWKs today — but that is a property of one producer rather than of this endpoint, and the private
11
+ * signing key behind this deployment mints the tokens the gateway verifies, so a `d` in this answer
12
+ * would hand the deployment to every caller who can log in (T-274). The same mapping the keystore
13
+ * below applies to its own keys, applied where the pair is published.
14
+ */
15
+ const publicJwk = (jwk: object): object =>
16
+ Object.fromEntries(Object.entries(jwk).filter(([name]) => !PRIVATE_JWK_MEMBERS.includes(name)));
17
+
18
+ export default library<{
19
+ keys: {
20
+ access: JWK;
21
+ id: JWK;
22
+ };
23
+ expire: Record<string, number>;
24
+ }>(
25
+ async ({
26
+ config: {
27
+ keys: {access, id},
28
+ expire,
29
+ },
30
+ lib: {writeRefresh},
31
+ gateway,
32
+ }) => {
33
+ const alg = access.alg || 'EdDSA';
34
+ const kid = access.kid || (await calculateJwkThumbprint(access));
35
+ const keyAccessToken = await importJWK(access, alg);
36
+ const jwks = {
37
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
38
+ keys: [access, id].filter(Boolean).map(({d, p, q, dp, dq, qi, ...pub}) => pub),
39
+ };
40
+ const keyStore = createLocalJWKSet(jwks);
41
+ // A process that serves nothing has no gateway to ask for its public keys — the `k8s` intent
42
+ // loads this realm for the plan's sake and serves no route at all — and the values are simply
43
+ // absent there rather than fatal. A process that signs tokens runs with a gateway.
44
+ const {public: keys} = gateway?.config?.() ?? {public: {sign: {}, encrypt: {}}};
45
+ return {
46
+ async jwks(
47
+ header: Parameters<typeof keyStore>[0] = {},
48
+ token: Parameters<typeof keyStore>[1],
49
+ ) {
50
+ return Object.keys(header).length ? keyStore(header, token) : jwks;
51
+ },
52
+ async token({
53
+ clientId,
54
+ actorId,
55
+ sessionId,
56
+ permissionMap,
57
+ mlek,
58
+ mlsk,
59
+ refresh,
60
+ actions,
61
+ profile,
62
+ ...rest
63
+ }: {
64
+ refresh?: number;
65
+ mlek?: object | 'header';
66
+ mlsk: object | 'header';
67
+ actions?: string[];
68
+ profile?: {actorId?: string; language?: string};
69
+ } & Record<string, unknown>) {
70
+ if (!refresh || refresh > expire.refresh) refresh = expire.refresh;
71
+ refresh = expire.never || refresh;
72
+ const access = expire.never || (expire.access > refresh ? refresh : expire.access);
73
+ return {
74
+ encrypt: publicJwk(keys.encrypt),
75
+ sign: publicJwk(keys.sign),
76
+ token_type: 'Bearer',
77
+ scope: 'openid',
78
+ session_id: sessionId,
79
+ ...(profile !== undefined && {profile}),
80
+ access_token: await new SignJWT({
81
+ ...rest,
82
+ typ: 'Bearer',
83
+ ses: sessionId,
84
+ per: permissionMap,
85
+ ...(mlek && {enc: mlek}),
86
+ ...(mlsk && {sig: mlsk}),
87
+ })
88
+ .setProtectedHeader({alg, kid})
89
+ .setIssuedAt()
90
+ .setSubject(String(actorId))
91
+ .setIssuer('blong-login')
92
+ .setAudience('blong')
93
+ .setExpirationTime(access + 's')
94
+ .sign(keyAccessToken),
95
+ expires_in: access,
96
+ refresh_token: writeRefresh({
97
+ actorId,
98
+ sessionId,
99
+ clientId,
100
+ mlsk,
101
+ mlek,
102
+ refresh,
103
+ actions,
104
+ ...rest,
105
+ }),
106
+ refresh_token_expires_in: refresh,
107
+ permissions: actions ?? true,
108
+ };
109
+ },
110
+ };
111
+ },
112
+ );
@@ -0,0 +1,17 @@
1
+ import {orchestrator} from '@feasibleone/blong';
2
+
3
+ export default orchestrator(blong => ({
4
+ extends: 'orchestrator.dispatch',
5
+ validation: blong.type.Object({
6
+ namespace: blong.type.String(),
7
+ imports: blong.type.Array(blong.type.String()),
8
+ validations: blong.type.Array(blong.type.String()),
9
+ }),
10
+ activation: {
11
+ default: {
12
+ namespace: 'login',
13
+ imports: ['login.login'],
14
+ validations: ['login.login.validation'],
15
+ },
16
+ },
17
+ }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feasibleone/blong-login",
3
- "version": "1.12.0",
3
+ "version": "1.13.0",
4
4
  "description": "Login and authentication utilities for the Blong framework",
5
5
  "keywords": [
6
6
  "blong",
@@ -28,7 +28,7 @@
28
28
  },
29
29
  "devDependencies": {
30
30
  "@feasibleone/blong": "^1.0.0",
31
- "@feasibleone/blong-dev": "1.9.0",
31
+ "@feasibleone/blong-dev": "1.10.0",
32
32
  "@rushstack/heft": "^1.2.6",
33
33
  "@rushstack/heft-lint-plugin": "^1.2.6",
34
34
  "@rushstack/heft-typescript-plugin": "^1.3.1",
package/server.ts ADDED
@@ -0,0 +1,124 @@
1
+ import {realm} from '@feasibleone/blong';
2
+
3
+ export default realm(blong => {
4
+ // Schema for one `login.methods.*` entry — a wire name (string) or `false`
5
+ // to disable that functionality. Shared by all methods so the union isn't
6
+ // repeated for each one.
7
+ const optionalMethod = () =>
8
+ blong.type.Optional(blong.type.Union([blong.type.String(), blong.type.Literal(false)]));
9
+ return {
10
+ url: import.meta.url,
11
+ validation: blong.type.Object({
12
+ login: blong.type.Object({
13
+ expire: blong.type.Object({
14
+ code: blong.type.Number(),
15
+ access: blong.type.Number(),
16
+ cookie: blong.type.Number(),
17
+ refresh: blong.type.Number(),
18
+ nonce: blong.type.Number(),
19
+ /** Inactivity timeout (s) — sessions idle longer are refused renewal. */
20
+ inactivity: blong.type.Number(),
21
+ /** Delete-after (s) — stale/revoked/expired sessions are purged. */
22
+ deleteAfter: blong.type.Number(),
23
+ }),
24
+ /**
25
+ * Wire names of the methods blong-login calls into the access realm.
26
+ * Defaults point at the blong-access handlers, so a suite can override
27
+ * them with its own implementations — or set a method to `false` to
28
+ * disable that functionality (lightweight suites without blong-access:
29
+ * e.g. `sessionCreate`/`sessionVerify`/… = false for stateless tokens,
30
+ * `auditRecord` = false to skip auditing).
31
+ */
32
+ methods: blong.type.Optional(
33
+ blong.type.Object({
34
+ credentialCheck: optionalMethod(),
35
+ credentialCheckClient: optionalMethod(),
36
+ identityCheck: optionalMethod(),
37
+ permissionList: optionalMethod(),
38
+ sessionCreate: optionalMethod(),
39
+ sessionVerify: optionalMethod(),
40
+ sessionRestore: optionalMethod(),
41
+ sessionRotate: optionalMethod(),
42
+ sessionClose: optionalMethod(),
43
+ sessionCleanup: optionalMethod(),
44
+ auditRecord: optionalMethod(),
45
+ }),
46
+ ),
47
+ /**
48
+ * Restore-cookie + session settings. `cookieName`/`cookiePath` let a
49
+ * suite rename/scope the opaque restore cookie; `isSecure`/`isHttpOnly`
50
+ * follow the defaults unless a deployment needs to relax them.
51
+ */
52
+ session: blong.type.Optional(
53
+ blong.type.Object({
54
+ cookieName: blong.type.Optional(blong.type.String()),
55
+ cookiePath: blong.type.Optional(blong.type.String()),
56
+ isSecure: blong.type.Optional(blong.type.Boolean()),
57
+ isHttpOnly: blong.type.Optional(blong.type.Boolean()),
58
+ }),
59
+ ),
60
+ cookie: blong.type.Object({
61
+ encoding: blong.type.String(),
62
+ isSecure: blong.type.Boolean(),
63
+ isHttpOnly: blong.type.Boolean(),
64
+ clearInvalid: blong.type.Boolean(),
65
+ strictHeader: blong.type.Boolean(),
66
+ }),
67
+ keys: blong.type.Object({
68
+ refresh: blong.type.String(),
69
+ access: blong.type.Object({
70
+ crv: blong.type.String(),
71
+ x: blong.type.String(),
72
+ d: blong.type.String(),
73
+ kty: blong.type.String(),
74
+ kid: blong.type.String(),
75
+ use: blong.type.String(),
76
+ alg: blong.type.String(),
77
+ }),
78
+ }),
79
+ }),
80
+ }),
81
+ config: {
82
+ default: {
83
+ login: {
84
+ expire: {
85
+ code: 60, // 1 minute
86
+ access: 15 * 60, // 15 minutes
87
+ cookie: 8 * 60 * 60, // 8 hours
88
+ refresh: 8 * 60 * 60, // 8 hours
89
+ nonce: 15 * 60, // 15 minute
90
+ inactivity: 30 * 60, // 30 minutes
91
+ deleteAfter: 24 * 60 * 60, // 24 hours
92
+ },
93
+ session: {
94
+ cookieName: 'blong.session',
95
+ cookiePath: '/rpc/login/token/restore',
96
+ isSecure: true,
97
+ isHttpOnly: true,
98
+ },
99
+ cookie: {
100
+ encoding: 'none',
101
+ isSecure: true,
102
+ isHttpOnly: true,
103
+ clearInvalid: false,
104
+ strictHeader: true,
105
+ },
106
+ keys: {
107
+ refresh: 'b1226b7ed6c6e5aded611ffb55a26a18154fb2263c8c2ea0974dd63e8e11919b',
108
+ access: {
109
+ crv: 'Ed25519',
110
+ x: 'hhcGW1iHk_YWlNYDxn7P4PGV1N6mPjghBge4O7zterQ',
111
+ d: 'KGpSfEzpbelEdQStQBlYmHPkHrG4cEcRx_yJZkRc_qY',
112
+ kty: 'OKP',
113
+ kid: 'kMfX1WoDc9dWVRugwGh9sSL956JS7yB8jE1ylo71Z-M',
114
+ use: 'sig',
115
+ alg: 'EdDSA',
116
+ },
117
+ },
118
+ },
119
+ },
120
+ dev: {},
121
+ integration: {},
122
+ },
123
+ };
124
+ });
@@ -0,0 +1,13 @@
1
+ import {handler} from '@feasibleone/blong';
2
+
3
+ export default handler(({lib: {group}}) => ({
4
+ testUserAdminLogin: ({name = 'login'}: {name: string}) =>
5
+ group(name)([
6
+ function createAdmin() {
7
+ return {username: 'sa', password: '123'};
8
+ },
9
+ function loginAdmin() {
10
+ return {accessToken: 'xxx'};
11
+ },
12
+ ]),
13
+ }));
package/tsconfig.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "compilerOptions": {
3
+ "rootDir": ".",
4
+ "allowJs": true,
5
+ "checkJs": false,
6
+ "moduleResolution": "bundler",
7
+ "esModuleInterop": true,
8
+ "module": "preserve",
9
+ "sourceMap": true,
10
+ "jsx": "react",
11
+ "allowImportingTsExtensions": true,
12
+ "noEmit": true,
13
+ "outDir": "dist",
14
+ "target": "ES2022",
15
+ "resolveJsonModule": true,
16
+ "strict": true
17
+ },
18
+ "ts-node": {
19
+ "esm": true,
20
+ "swc": true,
21
+ "transpileOnly": true,
22
+ "files": true,
23
+ "experimentalResolver": true
24
+ },
25
+ "include": ["./package.json", "**/*.ts"],
26
+ "exclude": ["node_modules", ".lint", ".docusaurus", "dist"]
27
+ }
@@ -0,0 +1,6 @@
1
+ declare module 'ut-function.cbc' {
2
+ export default function cbc(key: string | Buffer, validate?: boolean): {
3
+ encrypt(data: string | Buffer): Buffer;
4
+ decrypt(data: string | Buffer): string;
5
+ }
6
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "name": "@types/ut-function.cbc",
3
+ "version": "1.0.0"
4
+ }