@aooth/auth-moost 0.1.46 → 0.1.48

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/dist/index.d.mts CHANGED
@@ -1005,9 +1005,21 @@ interface TokenSuccess {
1005
1005
  access_token?: string;
1006
1006
  id_token?: string;
1007
1007
  expires_in?: number;
1008
+ /** Rotating refresh token — minted iff the grant's `TokenPolicy.refresh` opted in. */
1009
+ refresh_token?: string;
1008
1010
  /** The authenticated user id (`sub`) — convenience for a CLI; not part of the OIDC token response. */
1009
1011
  userId: string;
1010
1012
  }
1013
+ /** The `POST /auth/token` request body (RFC 6749 §4.1.3 / §6, form- or JSON-shaped). */
1014
+ interface TokenRequestBody {
1015
+ grant_type?: string;
1016
+ code?: string;
1017
+ code_verifier?: string;
1018
+ client_id?: string;
1019
+ client_secret?: string;
1020
+ refresh_token?: string;
1021
+ resource?: string | string[];
1022
+ }
1011
1023
  /** A minimal OIDC discovery document (`/.well-known/openid-configuration`). */
1012
1024
  interface OidcDiscoveryDocument {
1013
1025
  issuer: string;
@@ -1023,11 +1035,15 @@ interface OidcDiscoveryDocument {
1023
1035
  code_challenge_methods_supported: string[];
1024
1036
  token_endpoint_auth_methods_supported: string[];
1025
1037
  }
1026
- /** RFC 7591 §3.2.1 registration response — public client, so no secret fields. */
1038
+ /** RFC 7591 §3.2.1 registration response. Secret fields present iff a secret was issued. */
1027
1039
  interface ClientRegistrationSuccess {
1028
1040
  client_id: string;
1029
1041
  /** Seconds since epoch (the RFC's unit — NOT ms). */
1030
1042
  client_id_issued_at: number;
1043
+ /** The minted secret (`client_secret_post` registrations) — disclosed HERE and only here. */
1044
+ client_secret?: string;
1045
+ /** REQUIRED when a secret is issued; `0` ⇒ the secret does not expire. */
1046
+ client_secret_expires_at?: number;
1031
1047
  redirect_uris: string[];
1032
1048
  token_endpoint_auth_method: string;
1033
1049
  grant_types: string[];
@@ -1117,14 +1133,26 @@ declare class AuthorizeController {
1117
1133
  */
1118
1134
  protected scopesSupported(): string[] | undefined;
1119
1135
  authorize(responseType: string | undefined, redirectUri: string | undefined, clientId: string | undefined, state: string | undefined, codeChallenge: string | undefined, codeChallengeMethod: string | undefined, scope: string | undefined, nonce: string | undefined, resource: string | undefined): Promise<string>;
1120
- token(body: {
1121
- grant_type?: string;
1122
- code?: string;
1123
- code_verifier?: string;
1124
- client_id?: string;
1125
- client_secret?: string;
1126
- resource?: string | string[];
1127
- } | undefined): Promise<TokenSuccess | TokenError>;
1136
+ token(body: TokenRequestBody | undefined): Promise<TokenSuccess | TokenError>;
1137
+ /**
1138
+ * `grant_type=refresh_token` (OAuth 2.1 §4.3): rotate the presented refresh
1139
+ * token into a fresh access + refresh pair. Only a family minted BY this
1140
+ * token endpoint for a registered client redeems here — the
1141
+ * `metadata.authzClientId` stamp is the binding, checked BEFORE any rotation
1142
+ * (so a browser-session refresh token, or another client's, is a plain
1143
+ * `invalid_grant` with the family untouched). Client authentication mirrors
1144
+ * the code branch; the grant's authority (kind, payload, per-mint ttl) rides
1145
+ * the credential family — nothing is re-derived here. Reuse of an
1146
+ * already-rotated token revokes the whole family inside the session layer
1147
+ * (the standard theft response) and surfaces as `invalid_grant`.
1148
+ */
1149
+ protected refreshTokenGrant(body: TokenRequestBody): Promise<TokenSuccess | TokenError>;
1150
+ /**
1151
+ * Client authentication shared by both grant branches (RFC 6749 §2.3):
1152
+ * `true` iff the policy accepts the presented credentials (or defines no
1153
+ * `authenticateClient` hook). Callers map `false` to `401 invalid_client`.
1154
+ */
1155
+ protected clientAuthenticates(clientId: string, clientSecret: string | undefined): Promise<boolean>;
1128
1156
  /**
1129
1157
  * OIDC discovery (Tier 2). Derives every endpoint from the signer's `issuer`
1130
1158
  * (configured as `{origin}/auth`), so a relying `OidcProvider` configured with
@@ -1152,10 +1180,12 @@ declare class AuthorizeController {
1152
1180
  * RFC 7591 Dynamic Client Registration (OAUTH.md R2) — anonymous by spec;
1153
1181
  * 404 unless a registration operation is wired ({@link
1154
1182
  * getDynamicClientRegistration}). A thin HTTP adapter: validation, abuse
1155
- * knobs (guard / cap / never-used GC) and persistence live in
1156
- * `DynamicClientRegistration` (`@aooth/auth`). Public clients only — the
1157
- * response carries NO `client_secret` and NO `client_secret_expires_at`
1158
- * (RFC 7591 §3.2.1 requires them only when a secret is issued).
1183
+ * knobs (guard / cap / never-used GC), secret minting and persistence live
1184
+ * in `DynamicClientRegistration` (`@aooth/auth`). A `client_secret_post`
1185
+ * registration is echoed with its minted `client_secret` +
1186
+ * `client_secret_expires_at` — the ONE disclosure (only the hash is stored);
1187
+ * public (`"none"`) registrations carry neither field (RFC 7591 §3.2.1
1188
+ * requires them only when a secret is issued).
1159
1189
  */
1160
1190
  register(body: unknown): Promise<ClientRegistrationSuccess | ClientRegistrationFailure | TokenError>;
1161
1191
  /** The signer's public JWKS (Tier 2). 404 when no signer is wired. */
package/dist/index.mjs CHANGED
@@ -1,16 +1,16 @@
1
1
  import { C as Select2faForm, D as TermsBumpForm, E as StepUpConfirmForm, S as RemoveMfaConfirmForm, T as SignupForm, _ as PincodeForm, a as ConcurrencyLimitForm, c as EnrollConfirmForm, d as InviteForm, f as LoginCredentialsForm, g as PasswordReauthForm, h as MfaCodeForm, i as ChangePasswordForm, l as EnrollPickMethodForm, m as ManageMfaForm, n as AskPhoneForm, o as EmailIdentifierForm, r as AuthorizeConsentForm, s as EnrollAddressForm, t as AskEmailForm, u as EnrollTotpQrForm, v as ProveControlForm, w as SetPasswordForm, y as ProveControlOtpForm } from "./forms-xaBNc5Ng.mjs";
2
2
  import { Controller, HandlerPaths, Inherit, Inject, InjectMoostLogger, Injectable, Intercept, MoostInit, Optional, Param, Resolve, TInterceptorPriority, defineAfterInterceptor, defineBeforeInterceptor, getMoostMate, useControllerContext, useLogger } from "moost";
3
- import { AuthCredential, AuthError, RateLimitStoreMemory, RateLimiter, RateLimiter as RateLimiter$1, generateMagicLinkToken, parseRateLimitRule } from "@aooth/auth";
3
+ import { AuthCredential, AuthError, RateLimitStoreMemory, RateLimiter, RateLimiter as RateLimiter$1, generateMagicLinkToken, generateOpaqueToken, parseRateLimitRule } from "@aooth/auth";
4
4
  import { current, defineWook, eventTypeKey, key } from "@wooksjs/event-core";
5
5
  import { HttpError, useAuthorization, useCookies, useHeaders, useRequest, useResponse, useUrlParams } from "@wooksjs/event-http";
6
6
  import { ArbacAction, ArbacResource, getArbacMate, useArbac } from "@aooth/arbac-moost";
7
7
  import { FederatedIdentityStore, SEEN_DEVICES_DEFAULT_CAP, UserAuthError, UserService, generateMfaCode, generateTotpSecret, generateTotpUri, maskEmail, maskPhone, pickDefinedProfile, verifyTotpCode } from "@aooth/user";
8
8
  import { Body, Delete, Get, HttpError as HttpError$1, Post, Query } from "@moostjs/event-http";
9
- import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
9
+ import { createHash, timingSafeEqual } from "node:crypto";
10
10
  import { createAsHttpOutlet, finishWf, handleAsOutletRequest, useAtscriptWf } from "@atscript/moost-wf";
11
11
  import { EncapsulatedStateStrategy, MoostWf, Step, StepRetriableError, StepTTL, Workflow, WorkflowParam, WorkflowSchema, createEmailOutlet, outletEmail, swapStrategy, useWfFinished, useWfState } from "@moostjs/event-wf";
12
12
  import { FederatedLoginService, OAuthError, OAuthProviderRegistry, generateRandomState, pkceChallengeFor } from "@aooth/idp";
13
- import { ClientRegistrationError, DynamicClientRegistration, NoopOidcClaimsResolver, buildAuthorizationServerMetadata, buildAuthorizationServerMetadata as buildAuthorizationServerMetadata$1, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, canonicalizeIssuer as canonicalizeIssuer$1 } from "@aooth/auth/authz";
13
+ import { ClientRegistrationError, DynamicClientRegistration, NoopOidcClaimsResolver, buildAuthorizationServerMetadata, buildAuthorizationServerMetadata as buildAuthorizationServerMetadata$1, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, canonicalizeIssuer as canonicalizeIssuer$1, tokenPolicyToIssueOptions } from "@aooth/auth/authz";
14
14
  //#region \0@oxc-project+runtime@0.133.0/helpers/esm/decorate.js
15
15
  function __decorate(decorators, target, key, desc) {
16
16
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -7029,7 +7029,7 @@ let AuthorizeController = class AuthorizeController {
7029
7029
  if (resource !== void 0) {
7030
7030
  if (useUrlParams(current()).params().getAll("resource").length > 1 || resource.length > 2e3) return this.redirectError(resolved.redirectUri, "invalid_target", state);
7031
7031
  }
7032
- const binding = randomBytes(32).toString("base64url");
7032
+ const binding = generateOpaqueToken();
7033
7033
  const { handle, expiresAt } = await this.pending.create({
7034
7034
  ...resolved.clientId !== void 0 && { clientId: resolved.clientId },
7035
7035
  ...resolved.clientName !== void 0 && { clientName: resolved.clientName },
@@ -7057,6 +7057,7 @@ let AuthorizeController = class AuthorizeController {
7057
7057
  return "";
7058
7058
  }
7059
7059
  async token(body) {
7060
+ if (body?.grant_type === "refresh_token") return await this.refreshTokenGrant(body);
7060
7061
  const res = useResponse(current());
7061
7062
  if (body?.grant_type !== "authorization_code") {
7062
7063
  res.status = 400;
@@ -7080,12 +7081,7 @@ let AuthorizeController = class AuthorizeController {
7080
7081
  res.status = 401;
7081
7082
  return { error: "invalid_client" };
7082
7083
  }
7083
- try {
7084
- await this.policy.authenticateClient?.({
7085
- clientId: row.clientId,
7086
- ...body.client_secret !== void 0 && { clientSecret: body.client_secret }
7087
- });
7088
- } catch {
7084
+ if (!await this.clientAuthenticates(row.clientId, body.client_secret)) {
7089
7085
  res.status = 401;
7090
7086
  return { error: "invalid_client" };
7091
7087
  }
@@ -7122,10 +7118,12 @@ let AuthorizeController = class AuthorizeController {
7122
7118
  }
7123
7119
  let accessToken;
7124
7120
  let expiresIn;
7121
+ let refreshToken;
7125
7122
  if (wantAccessToken) {
7126
- const issued = await this.auth.issue(row.userId, tokenPolicyToIssueOptions(row.tokenPolicy));
7123
+ const issued = await this.auth.issue(row.userId, tokenPolicyToIssueOptions(row.tokenPolicy, row.clientId));
7127
7124
  accessToken = issued.accessToken;
7128
- expiresIn = Math.max(0, Math.floor((issued.accessExpiresAt - Date.now()) / 1e3));
7125
+ expiresIn = expiresInSeconds(issued.accessExpiresAt);
7126
+ refreshToken = issued.refreshToken;
7129
7127
  }
7130
7128
  let idToken;
7131
7129
  if (signing) {
@@ -7144,11 +7142,73 @@ let AuthorizeController = class AuthorizeController {
7144
7142
  access_token: accessToken,
7145
7143
  expires_in: expiresIn
7146
7144
  },
7145
+ ...refreshToken !== void 0 && { refresh_token: refreshToken },
7147
7146
  ...idToken !== void 0 && { id_token: idToken },
7148
7147
  userId: row.userId
7149
7148
  };
7150
7149
  }
7151
7150
  /**
7151
+ * `grant_type=refresh_token` (OAuth 2.1 §4.3): rotate the presented refresh
7152
+ * token into a fresh access + refresh pair. Only a family minted BY this
7153
+ * token endpoint for a registered client redeems here — the
7154
+ * `metadata.authzClientId` stamp is the binding, checked BEFORE any rotation
7155
+ * (so a browser-session refresh token, or another client's, is a plain
7156
+ * `invalid_grant` with the family untouched). Client authentication mirrors
7157
+ * the code branch; the grant's authority (kind, payload, per-mint ttl) rides
7158
+ * the credential family — nothing is re-derived here. Reuse of an
7159
+ * already-rotated token revokes the whole family inside the session layer
7160
+ * (the standard theft response) and surfaces as `invalid_grant`.
7161
+ */
7162
+ async refreshTokenGrant(body) {
7163
+ const res = useResponse(current());
7164
+ if (typeof body.refresh_token !== "string" || body.refresh_token.length === 0) {
7165
+ res.status = 400;
7166
+ return { error: "invalid_request" };
7167
+ }
7168
+ const clientId = body.client_id;
7169
+ if (typeof clientId !== "string" || clientId.length === 0) {
7170
+ res.status = 401;
7171
+ return { error: "invalid_client" };
7172
+ }
7173
+ if (!await this.clientAuthenticates(clientId, body.client_secret)) {
7174
+ res.status = 401;
7175
+ return { error: "invalid_client" };
7176
+ }
7177
+ let issued;
7178
+ try {
7179
+ issued = await this.auth.refresh(body.refresh_token, { guard: (state) => {
7180
+ if (state.metadata?.authzClientId !== clientId) throw new Error("refresh token was not issued to this client");
7181
+ } });
7182
+ } catch {
7183
+ res.status = 400;
7184
+ return { error: "invalid_grant" };
7185
+ }
7186
+ res.status = 200;
7187
+ return {
7188
+ token_type: "Bearer",
7189
+ access_token: issued.accessToken,
7190
+ expires_in: expiresInSeconds(issued.accessExpiresAt),
7191
+ ...issued.refreshToken !== void 0 && { refresh_token: issued.refreshToken },
7192
+ userId: issued.userId
7193
+ };
7194
+ }
7195
+ /**
7196
+ * Client authentication shared by both grant branches (RFC 6749 §2.3):
7197
+ * `true` iff the policy accepts the presented credentials (or defines no
7198
+ * `authenticateClient` hook). Callers map `false` to `401 invalid_client`.
7199
+ */
7200
+ async clientAuthenticates(clientId, clientSecret) {
7201
+ try {
7202
+ await this.policy.authenticateClient?.({
7203
+ clientId,
7204
+ ...clientSecret !== void 0 && { clientSecret }
7205
+ });
7206
+ return true;
7207
+ } catch {
7208
+ return false;
7209
+ }
7210
+ }
7211
+ /**
7152
7212
  * OIDC discovery (Tier 2). Derives every endpoint from the signer's `issuer`
7153
7213
  * (configured as `{origin}/auth`), so a relying `OidcProvider` configured with
7154
7214
  * the same `issuer` resolves `/authorize`, `/token`, and `/jwks` automatically.
@@ -7172,7 +7232,7 @@ let AuthorizeController = class AuthorizeController {
7172
7232
  jwks_uri: `${iss}/jwks`,
7173
7233
  ...this.getDynamicClientRegistration() && { registration_endpoint: `${iss}/register` },
7174
7234
  response_types_supported: ["code"],
7175
- grant_types_supported: ["authorization_code"],
7235
+ grant_types_supported: ["authorization_code", "refresh_token"],
7176
7236
  subject_types_supported: ["public"],
7177
7237
  id_token_signing_alg_values_supported: [signer.alg],
7178
7238
  scopes_supported: [
@@ -7215,10 +7275,12 @@ let AuthorizeController = class AuthorizeController {
7215
7275
  * RFC 7591 Dynamic Client Registration (OAUTH.md R2) — anonymous by spec;
7216
7276
  * 404 unless a registration operation is wired ({@link
7217
7277
  * getDynamicClientRegistration}). A thin HTTP adapter: validation, abuse
7218
- * knobs (guard / cap / never-used GC) and persistence live in
7219
- * `DynamicClientRegistration` (`@aooth/auth`). Public clients only — the
7220
- * response carries NO `client_secret` and NO `client_secret_expires_at`
7221
- * (RFC 7591 §3.2.1 requires them only when a secret is issued).
7278
+ * knobs (guard / cap / never-used GC), secret minting and persistence live
7279
+ * in `DynamicClientRegistration` (`@aooth/auth`). A `client_secret_post`
7280
+ * registration is echoed with its minted `client_secret` +
7281
+ * `client_secret_expires_at` — the ONE disclosure (only the hash is stored);
7282
+ * public (`"none"`) registrations carry neither field (RFC 7591 §3.2.1
7283
+ * requires them only when a secret is issued).
7222
7284
  */
7223
7285
  async register(body) {
7224
7286
  const res = useResponse(current());
@@ -7240,6 +7302,10 @@ let AuthorizeController = class AuthorizeController {
7240
7302
  return {
7241
7303
  client_id: client.clientId,
7242
7304
  client_id_issued_at: Math.floor(client.createdAt / 1e3),
7305
+ ...client.clientSecret !== void 0 && {
7306
+ client_secret: client.clientSecret,
7307
+ client_secret_expires_at: client.clientSecretExpiresAt
7308
+ },
7243
7309
  redirect_uris: client.redirectUris,
7244
7310
  token_endpoint_auth_method: client.tokenEndpointAuthMethod,
7245
7311
  grant_types: client.grantTypes,
@@ -7355,13 +7421,9 @@ AuthorizeController = __decorate([
7355
7421
  Object
7356
7422
  ])
7357
7423
  ], AuthorizeController);
7358
- /** Flatten a {@link TokenPolicy} into the `issue()` options it forwards. */
7359
- function tokenPolicyToIssueOptions(policy) {
7360
- return {
7361
- ...policy.payload,
7362
- ...policy.kind !== void 0 && { kind: policy.kind },
7363
- ...policy.ttl !== void 0 && { ttl: policy.ttl }
7364
- };
7424
+ /** RFC 6749 `expires_in`: whole seconds from now until `expiresAt`, floored at 0. */
7425
+ function expiresInSeconds(expiresAt) {
7426
+ return Math.max(0, Math.floor((expiresAt - Date.now()) / 1e3));
7365
7427
  }
7366
7428
  //#endregion
7367
7429
  //#region src/workflows/auth-email-outlet.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aooth/auth-moost",
3
- "version": "0.1.46",
3
+ "version": "0.1.48",
4
4
  "description": "Moost auth integration for aoothjs — AuthGuard interceptor, useAuth composable, REST endpoints, workflows",
5
5
  "keywords": [
6
6
  "aoothjs",
@@ -57,33 +57,33 @@
57
57
  "access": "public"
58
58
  },
59
59
  "dependencies": {
60
- "@atscript/moost-wf": "^0.1.120",
60
+ "@atscript/moost-wf": "^0.1.121",
61
61
  "@wooksjs/http-body": "^0.7.19",
62
- "@aooth/arbac-moost": "^0.1.46",
63
- "@aooth/auth": "0.1.46",
64
- "@aooth/idp": "0.1.46",
65
- "@aooth/user": "0.1.46"
62
+ "@aooth/arbac-moost": "^0.1.48",
63
+ "@aooth/auth": "0.1.48",
64
+ "@aooth/idp": "0.1.48",
65
+ "@aooth/user": "0.1.48"
66
66
  },
67
67
  "devDependencies": {
68
- "@atscript/core": "^0.1.81",
69
- "@atscript/typescript": "^0.1.81",
70
- "@atscript/ui": "^0.1.120",
71
- "@atscript/ui-fns": "^0.1.120",
72
- "@moostjs/event-http": "^0.6.29",
73
- "@moostjs/event-wf": "^0.6.29",
74
- "moost": "^0.6.29",
75
- "unplugin-atscript": "^0.1.81",
68
+ "@atscript/core": "^0.1.82",
69
+ "@atscript/typescript": "^0.1.82",
70
+ "@atscript/ui": "^0.1.121",
71
+ "@atscript/ui-fns": "^0.1.121",
72
+ "@moostjs/event-http": "^0.6.30",
73
+ "@moostjs/event-wf": "^0.6.30",
74
+ "moost": "^0.6.30",
75
+ "unplugin-atscript": "^0.1.82",
76
76
  "wooks": "^0.7.19"
77
77
  },
78
78
  "peerDependencies": {
79
- "@atscript/moost-wf": "^0.1.120",
80
- "@atscript/typescript": "^0.1.81",
81
- "@moostjs/event-http": "^0.6.29",
82
- "@moostjs/event-wf": "^0.6.29",
79
+ "@atscript/moost-wf": "^0.1.121",
80
+ "@atscript/typescript": "^0.1.82",
81
+ "@moostjs/event-http": "^0.6.30",
82
+ "@moostjs/event-wf": "^0.6.30",
83
83
  "@wooksjs/event-core": "^0.7.19",
84
84
  "@wooksjs/event-http": "^0.7.19",
85
85
  "@wooksjs/http-body": "^0.7.19",
86
- "moost": "^0.6.29"
86
+ "moost": "^0.6.30"
87
87
  },
88
88
  "peerDependenciesMeta": {
89
89
  "@atscript/typescript": {