@venturekit/auth 0.0.50 → 0.0.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +8 -7
  2. package/dist/index.d.ts +1 -2
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +1 -2
  5. package/dist/index.js.map +1 -1
  6. package/dist/migrations/vk_auth_006_verification_code_issuance.sql +29 -0
  7. package/dist/server/api-keys.d.ts +10 -5
  8. package/dist/server/api-keys.d.ts.map +1 -1
  9. package/dist/server/api-keys.js +24 -8
  10. package/dist/server/api-keys.js.map +1 -1
  11. package/dist/server/config.d.ts +6 -0
  12. package/dist/server/config.d.ts.map +1 -1
  13. package/dist/server/config.js +2 -0
  14. package/dist/server/config.js.map +1 -1
  15. package/dist/server/cookies.d.ts +9 -5
  16. package/dist/server/cookies.d.ts.map +1 -1
  17. package/dist/server/cookies.js +19 -6
  18. package/dist/server/cookies.js.map +1 -1
  19. package/dist/server/errors.d.ts +18 -2
  20. package/dist/server/errors.d.ts.map +1 -1
  21. package/dist/server/errors.js +46 -3
  22. package/dist/server/errors.js.map +1 -1
  23. package/dist/server/federated/account-linking.d.ts +90 -0
  24. package/dist/server/federated/account-linking.d.ts.map +1 -0
  25. package/dist/server/federated/account-linking.js +78 -0
  26. package/dist/server/federated/account-linking.js.map +1 -0
  27. package/dist/server/federated/authorization.d.ts +81 -0
  28. package/dist/server/federated/authorization.d.ts.map +1 -0
  29. package/dist/server/federated/authorization.js +229 -0
  30. package/dist/server/federated/authorization.js.map +1 -0
  31. package/dist/server/federated/credentials.d.ts +22 -0
  32. package/dist/server/federated/credentials.d.ts.map +1 -0
  33. package/dist/server/federated/credentials.js +81 -0
  34. package/dist/server/federated/credentials.js.map +1 -0
  35. package/dist/server/federated/oauth-transaction.d.ts +54 -0
  36. package/dist/server/federated/oauth-transaction.d.ts.map +1 -0
  37. package/dist/server/federated/oauth-transaction.js +92 -0
  38. package/dist/server/federated/oauth-transaction.js.map +1 -0
  39. package/dist/server/federated/providers.d.ts +34 -0
  40. package/dist/server/federated/providers.d.ts.map +1 -0
  41. package/dist/server/federated/providers.js +65 -0
  42. package/dist/server/federated/providers.js.map +1 -0
  43. package/dist/server/federated/sign-in.d.ts +81 -0
  44. package/dist/server/federated/sign-in.d.ts.map +1 -0
  45. package/dist/server/federated/sign-in.js +180 -0
  46. package/dist/server/federated/sign-in.js.map +1 -0
  47. package/dist/server/federated/types.d.ts +36 -0
  48. package/dist/server/federated/types.d.ts.map +1 -0
  49. package/dist/server/federated/types.js +5 -0
  50. package/dist/server/federated/types.js.map +1 -0
  51. package/dist/server/federated-routes.d.ts +15 -7
  52. package/dist/server/federated-routes.d.ts.map +1 -1
  53. package/dist/server/federated-routes.js +27 -16
  54. package/dist/server/federated-routes.js.map +1 -1
  55. package/dist/server/federated.d.ts +25 -196
  56. package/dist/server/federated.d.ts.map +1 -1
  57. package/dist/server/federated.js +19 -521
  58. package/dist/server/federated.js.map +1 -1
  59. package/dist/server/forgot-password.d.ts +4 -3
  60. package/dist/server/forgot-password.d.ts.map +1 -1
  61. package/dist/server/forgot-password.js +3 -5
  62. package/dist/server/forgot-password.js.map +1 -1
  63. package/dist/server/handoff-routes.d.ts +16 -5
  64. package/dist/server/handoff-routes.d.ts.map +1 -1
  65. package/dist/server/handoff-routes.js +23 -11
  66. package/dist/server/handoff-routes.js.map +1 -1
  67. package/dist/server/impersonation.d.ts +6 -3
  68. package/dist/server/impersonation.d.ts.map +1 -1
  69. package/dist/server/impersonation.js +11 -5
  70. package/dist/server/impersonation.js.map +1 -1
  71. package/dist/server/index.d.ts +5 -2
  72. package/dist/server/index.d.ts.map +1 -1
  73. package/dist/server/index.js +2 -1
  74. package/dist/server/index.js.map +1 -1
  75. package/dist/server/invitations.d.ts +6 -2
  76. package/dist/server/invitations.d.ts.map +1 -1
  77. package/dist/server/invitations.js +6 -3
  78. package/dist/server/invitations.js.map +1 -1
  79. package/dist/server/local-cognito.d.ts +19 -0
  80. package/dist/server/local-cognito.d.ts.map +1 -0
  81. package/dist/server/local-cognito.js +19 -0
  82. package/dist/server/local-cognito.js.map +1 -0
  83. package/dist/server/refresh.d.ts +23 -12
  84. package/dist/server/refresh.d.ts.map +1 -1
  85. package/dist/server/refresh.js +35 -19
  86. package/dist/server/refresh.js.map +1 -1
  87. package/dist/server/resource-scope.d.ts +19 -0
  88. package/dist/server/resource-scope.d.ts.map +1 -0
  89. package/dist/server/resource-scope.js +2 -0
  90. package/dist/server/resource-scope.js.map +1 -0
  91. package/dist/server/route-rate-limit.d.ts +50 -0
  92. package/dist/server/route-rate-limit.d.ts.map +1 -0
  93. package/dist/server/route-rate-limit.js +39 -0
  94. package/dist/server/route-rate-limit.js.map +1 -0
  95. package/dist/server/session-routes.d.ts +9 -2
  96. package/dist/server/session-routes.d.ts.map +1 -1
  97. package/dist/server/session-routes.js +6 -4
  98. package/dist/server/session-routes.js.map +1 -1
  99. package/dist/server/sign-up.d.ts +32 -17
  100. package/dist/server/sign-up.d.ts.map +1 -1
  101. package/dist/server/sign-up.js +30 -12
  102. package/dist/server/sign-up.js.map +1 -1
  103. package/dist/server/store/postgres.d.ts.map +1 -1
  104. package/dist/server/store/postgres.js +43 -27
  105. package/dist/server/store/postgres.js.map +1 -1
  106. package/dist/server/verification.d.ts +76 -33
  107. package/dist/server/verification.d.ts.map +1 -1
  108. package/dist/server/verification.js +68 -67
  109. package/dist/server/verification.js.map +1 -1
  110. package/dist/server/verify.d.ts.map +1 -1
  111. package/dist/server/verify.js +8 -3
  112. package/dist/server/verify.js.map +1 -1
  113. package/dist/session/index.d.ts +11 -13
  114. package/dist/session/index.d.ts.map +1 -1
  115. package/dist/session/index.js +13 -14
  116. package/dist/session/index.js.map +1 -1
  117. package/package.json +6 -6
  118. package/src/migrations/vk_auth_006_verification_code_issuance.sql +29 -0
@@ -1,47 +1,63 @@
1
1
  /**
2
2
  * Server-side refresh-token flow against a Cognito User Pool.
3
3
  *
4
- * Uses the `REFRESH_TOKEN_AUTH` flow to swap a refresh token for a fresh
5
- * id+access token pair. Cognito does NOT rotate the refresh token by
6
- * default; the same one stays valid until its User-Pool-configured TTL
7
- * or until {@link revokeRefreshToken} is called — so the returned
8
- * `refreshToken` is always the empty string.
4
+ * Two shapes, chosen by the app client's configuration:
5
+ *
6
+ * - **Rotation on** (`auth[].clients[].refreshTokenRotation`, surfaced as
7
+ * `AuthServerConfig.refreshTokenRotation`): `GetTokensFromRefreshToken`
8
+ * returns a NEW refresh token every time and retires the old one after
9
+ * the grace period, so a session lasts as long as it is used — the
10
+ * validity becomes inactivity — and a stolen refresh token dies at the
11
+ * owner's next refresh. Presenting a retired token outside the grace
12
+ * period revokes the whole family: {@link AuthError} `refresh_token_reused`.
13
+ * - **Rotation off**: `InitiateAuth REFRESH_TOKEN_AUTH`, which never
14
+ * rotates; the refresh token stays valid for its fixed lifetime.
15
+ *
16
+ * {@link RefreshResult.refreshToken} is the token to keep: the new one
17
+ * under rotation, `''` (keep the one you have) otherwise.
9
18
  */
10
- import { InitiateAuthCommand } from '@aws-sdk/client-cognito-identity-provider';
19
+ import { GetTokensFromRefreshTokenCommand, InitiateAuthCommand } from '@aws-sdk/client-cognito-identity-provider';
11
20
  import { loadAuthServerConfig } from './config.js';
12
21
  import { getCognitoClient } from './cognito-client.js';
13
22
  import { AuthError, mapProviderError } from './errors.js';
23
+ import { isLocalCognito } from './local-cognito.js';
14
24
  import { deriveExpiresInFromJwt } from './token-utils.js';
15
25
  /**
16
- * Exchange a refresh token for fresh id + access tokens.
26
+ * Exchange a refresh token for fresh id + access tokens (and, under
27
+ * rotation, a fresh refresh token).
17
28
  *
18
- * Throws {@link AuthError} when the refresh token is expired / revoked
19
- * / malformed; route handlers should clear session cookies on terminal
20
- * failures so the user is redirected straight to sign-in.
29
+ * Throws {@link AuthError} when the refresh token is expired / revoked /
30
+ * malformed (`refresh_failed`), or was already rotated out
31
+ * (`refresh_token_reused` — Cognito has revoked the family). Route
32
+ * handlers should clear session cookies on either.
21
33
  */
22
34
  export async function refreshSession(refreshToken, config = loadAuthServerConfig()) {
23
35
  const client = getCognitoClient(config.region, config.endpoint);
24
- let res;
36
+ // cognito-local implements only REFRESH_TOKEN_AUTH: `vk dev` keeps it.
37
+ const rotate = config.refreshTokenRotation === true && !isLocalCognito(config);
38
+ let result;
25
39
  try {
26
- res = await client.send(new InitiateAuthCommand({
27
- ClientId: config.appClientId,
28
- AuthFlow: 'REFRESH_TOKEN_AUTH',
29
- AuthParameters: { REFRESH_TOKEN: refreshToken },
30
- }));
40
+ result = rotate
41
+ ? (await client.send(new GetTokensFromRefreshTokenCommand({ ClientId: config.appClientId, RefreshToken: refreshToken })))
42
+ .AuthenticationResult
43
+ : (await client.send(new InitiateAuthCommand({
44
+ ClientId: config.appClientId,
45
+ AuthFlow: 'REFRESH_TOKEN_AUTH',
46
+ AuthParameters: { REFRESH_TOKEN: refreshToken },
47
+ }))).AuthenticationResult;
31
48
  }
32
49
  catch (err) {
33
50
  throw mapProviderError(err, 'refresh_failed');
34
51
  }
35
- const result = res.AuthenticationResult;
36
52
  // Tokens MUST be present; `ExpiresIn` is derived from the access
37
53
  // token's `exp` claim when the provider omits it (see `sign-in.ts`).
38
- if (!result?.IdToken || !result.AccessToken) {
54
+ if (!result?.IdToken || !result.AccessToken || (rotate && !result.RefreshToken)) {
39
55
  throw new AuthError('incomplete_auth_result', 'Identity provider returned an incomplete refresh result', 500);
40
56
  }
41
57
  return {
42
58
  idToken: result.IdToken,
43
59
  accessToken: result.AccessToken,
44
- refreshToken: '',
60
+ refreshToken: rotate ? result.RefreshToken : '',
45
61
  expiresIn: result.ExpiresIn ?? deriveExpiresInFromJwt(result.AccessToken),
46
62
  };
47
63
  }
@@ -1 +1 @@
1
- {"version":3,"file":"refresh.js","sourceRoot":"","sources":["../../src/server/refresh.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,2CAA2C,CAAC;AAEhF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,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,gBAAgB,CAAC,GAAG,EAAE,gBAAgB,CAAC,CAAC;IAChD,CAAC;IACD,iEAAiE;IACjE,qEAAqE;IACrE,IAAI,CAAC,MAAM,EAAE,OAAO,IAAI,CAAC,MAAM,CAAC,WAAW,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,CAAC;QAChF,MAAM,IAAI,SAAS,CAAC,wBAAwB,EAAE,yDAAyD,EAAE,GAAG,CAAC,CAAC;IAChH,CAAC;IACD,OAAO;QACL,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,WAAW,EAAE,MAAM,CAAC,WAAW;QAC/B,YAAY,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,YAAa,CAAC,CAAC,CAAC,EAAE;QAChD,SAAS,EAAE,MAAM,CAAC,SAAS,IAAI,sBAAsB,CAAC,MAAM,CAAC,WAAW,CAAC;KAC1E,CAAC;AACJ,CAAC"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The scope a by-id operation on a tenant-owned record is confined to.
3
+ *
4
+ * Ids arrive from requests. An operation that takes only an id lets a
5
+ * caller in one tenant act on another tenant's record (broken object-level
6
+ * authorization) the moment a route forgets its own ownership check. Every
7
+ * by-id helper in this package therefore takes a scope and matches it in
8
+ * the same statement that reads or writes the row.
9
+ */
10
+ export interface TenantScope {
11
+ /** Records of this tenant only; `null` = tenant-less records only. */
12
+ tenantId: string | null;
13
+ }
14
+ /** A {@link TenantScope} optionally narrowed to one owner's records. */
15
+ export interface OwnedScope extends TenantScope {
16
+ /** When set, records owned by this principal only. */
17
+ ownerId?: string;
18
+ }
19
+ //# sourceMappingURL=resource-scope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resource-scope.d.ts","sourceRoot":"","sources":["../../src/server/resource-scope.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,MAAM,WAAW,WAAW;IAC1B,sEAAsE;IACtE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB;AAED,wEAAwE;AACxE,MAAM,WAAW,UAAW,SAAQ,WAAW;IAC7C,sDAAsD;IACtD,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=resource-scope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resource-scope.js","sourceRoot":"","sources":["../../src/server/resource-scope.ts"],"names":[],"mappings":""}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The per-client rate limit every `@venturekit/auth` route factory applies
3
+ * out of the box (sign-in starts and callbacks, refresh, logout, handoff).
4
+ *
5
+ * Authentication endpoints are public and drive paid / sensitive work
6
+ * (Cognito calls, IdP round-trips, token minting), so they are limited by
7
+ * default rather than left to each app to remember. Limits are per client
8
+ * IP and per route, generous enough for a campus or office behind one NAT;
9
+ * a factory's `rateLimit` option tunes them, and `false` disables them
10
+ * (explicitly — e.g. when the app already limits at its edge).
11
+ *
12
+ * The store is the runtime default (DynamoDB on Lambda, memory under
13
+ * `vk dev`). It fails OPEN: if the store itself is unreachable, signing
14
+ * in keeps working and the error is logged.
15
+ */
16
+ import { type Middleware, type RequestContext } from '@venturekit/runtime';
17
+ export interface AuthRouteRateLimit {
18
+ /** Requests allowed per client IP in each window. */
19
+ limit: number;
20
+ /** Window length in milliseconds. */
21
+ windowMs: number;
22
+ }
23
+ /** A factory's `rateLimit` option: tune the defaults, or `false` to disable. */
24
+ export type AuthRouteRateLimitOption = Partial<AuthRouteRateLimit> | false;
25
+ /** The limiter middleware for one auth route (empty when disabled). */
26
+ export declare function authRouteRateLimit(name: string, option: AuthRouteRateLimitOption | undefined, defaults: AuthRouteRateLimit): Middleware<RequestContext>[];
27
+ /** Built-in limits per route. */
28
+ export declare const AUTH_ROUTE_RATE_LIMITS: Readonly<{
29
+ federatedStart: {
30
+ limit: number;
31
+ windowMs: number;
32
+ };
33
+ federatedCallback: {
34
+ limit: number;
35
+ windowMs: number;
36
+ };
37
+ logout: {
38
+ limit: number;
39
+ windowMs: number;
40
+ };
41
+ refresh: {
42
+ limit: number;
43
+ windowMs: number;
44
+ };
45
+ handoff: {
46
+ limit: number;
47
+ windowMs: number;
48
+ };
49
+ }>;
50
+ //# sourceMappingURL=route-rate-limit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-rate-limit.d.ts","sourceRoot":"","sources":["../../src/server/route-rate-limit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAA8B,KAAK,UAAU,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAEvG,MAAM,WAAW,kBAAkB;IACjC,qDAAqD;IACrD,KAAK,EAAE,MAAM,CAAC;IACd,qCAAqC;IACrC,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,gFAAgF;AAChF,MAAM,MAAM,wBAAwB,GAAG,OAAO,CAAC,kBAAkB,CAAC,GAAG,KAAK,CAAC;AAE3E,uEAAuE;AACvE,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,wBAAwB,GAAG,SAAS,EAC5C,QAAQ,EAAE,kBAAkB,GAC3B,UAAU,CAAC,cAAc,CAAC,EAAE,CAU9B;AAID,iCAAiC;AACjC,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;;;;;EAMY,CAAC"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The per-client rate limit every `@venturekit/auth` route factory applies
3
+ * out of the box (sign-in starts and callbacks, refresh, logout, handoff).
4
+ *
5
+ * Authentication endpoints are public and drive paid / sensitive work
6
+ * (Cognito calls, IdP round-trips, token minting), so they are limited by
7
+ * default rather than left to each app to remember. Limits are per client
8
+ * IP and per route, generous enough for a campus or office behind one NAT;
9
+ * a factory's `rateLimit` option tunes them, and `false` disables them
10
+ * (explicitly — e.g. when the app already limits at its edge).
11
+ *
12
+ * The store is the runtime default (DynamoDB on Lambda, memory under
13
+ * `vk dev`). It fails OPEN: if the store itself is unreachable, signing
14
+ * in keeps working and the error is logged.
15
+ */
16
+ import { defaultRateLimitMiddleware } from '@venturekit/runtime';
17
+ /** The limiter middleware for one auth route (empty when disabled). */
18
+ export function authRouteRateLimit(name, option, defaults) {
19
+ if (option === false)
20
+ return [];
21
+ return [
22
+ defaultRateLimitMiddleware({
23
+ name: `vk-auth:${name}`,
24
+ limit: option?.limit ?? defaults.limit,
25
+ windowMs: option?.windowMs ?? defaults.windowMs,
26
+ onError: 'open',
27
+ }),
28
+ ];
29
+ }
30
+ const MINUTE = 60_000;
31
+ /** Built-in limits per route. */
32
+ export const AUTH_ROUTE_RATE_LIMITS = Object.freeze({
33
+ federatedStart: { limit: 30, windowMs: MINUTE },
34
+ federatedCallback: { limit: 30, windowMs: MINUTE },
35
+ logout: { limit: 60, windowMs: MINUTE },
36
+ refresh: { limit: 120, windowMs: MINUTE },
37
+ handoff: { limit: 60, windowMs: MINUTE },
38
+ });
39
+ //# sourceMappingURL=route-rate-limit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-rate-limit.js","sourceRoot":"","sources":["../../src/server/route-rate-limit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,0BAA0B,EAAwC,MAAM,qBAAqB,CAAC;AAYvG,uEAAuE;AACvE,MAAM,UAAU,kBAAkB,CAChC,IAAY,EACZ,MAA4C,EAC5C,QAA4B;IAE5B,IAAI,MAAM,KAAK,KAAK;QAAE,OAAO,EAAE,CAAC;IAChC,OAAO;QACL,0BAA0B,CAAC;YACzB,IAAI,EAAE,WAAW,IAAI,EAAE;YACvB,KAAK,EAAE,MAAM,EAAE,KAAK,IAAI,QAAQ,CAAC,KAAK;YACtC,QAAQ,EAAE,MAAM,EAAE,QAAQ,IAAI,QAAQ,CAAC,QAAQ;YAC/C,OAAO,EAAE,MAAM;SAChB,CAAC;KACH,CAAC;AACJ,CAAC;AAED,MAAM,MAAM,GAAG,MAAM,CAAC;AAEtB,iCAAiC;AACjC,MAAM,CAAC,MAAM,sBAAsB,GAAG,MAAM,CAAC,MAAM,CAAC;IAClD,cAAc,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE;IAC/C,iBAAiB,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE;IAClD,MAAM,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE;IACvC,OAAO,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE;IACzC,OAAO,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE;CACI,CAAC,CAAC"}
@@ -18,7 +18,8 @@
18
18
  *
19
19
  * Both routes must live under the refresh cookie's Path, or the browser
20
20
  * never sends it to them. They are public (no `scopes`): the refresh
21
- * cookie is the credential. Add a rate limiter through `middleware`.
21
+ * cookie is the credential. Both are rate-limited per client IP by
22
+ * default (`rateLimit`).
22
23
  *
23
24
  * ```ts
24
25
  * // src/lib/admin-session.ts
@@ -41,6 +42,7 @@ import type { APIGatewayProxyEventV2, APIGatewayProxyResultV2, Context as Lambda
41
42
  import { type Middleware, type RequestContext } from '@venturekit/runtime';
42
43
  import { type CookieOptions } from './cookies.js';
43
44
  import { type AuthServerConfig } from './config.js';
45
+ import { type AuthRouteRateLimitOption } from './route-rate-limit.js';
44
46
  export interface SessionRoutesOptions {
45
47
  /**
46
48
  * The session's cookies — names, paths, Domain, persistence — exactly as
@@ -52,8 +54,13 @@ export interface SessionRoutesOptions {
52
54
  cookieOptions?: CookieOptions | ((ctx: RequestContext) => CookieOptions);
53
55
  /** Explicit Cognito config; defaults to env-var loading per request. */
54
56
  config?: AuthServerConfig;
55
- /** Extra middleware for both routes (rate limiting, CORS, …). */
57
+ /** Extra middleware for both routes (CORS, tenancy, …). */
56
58
  middleware?: Middleware<RequestContext>[];
59
+ /**
60
+ * Per-client-IP limits: refresh 120/min, logout 60/min by default.
61
+ * Tune them, or `false` to disable (e.g. limited at the edge already).
62
+ */
63
+ rateLimit?: AuthRouteRateLimitOption;
57
64
  }
58
65
  export interface SessionRoutes {
59
66
  refresh: (event: APIGatewayProxyEventV2, context: LambdaContext) => Promise<APIGatewayProxyResultV2>;
@@ -1 +1 @@
1
- {"version":3,"file":"session-routes.d.ts","sourceRoot":"","sources":["../../src/server/session-routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,OAAO,KAAK,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,YAAY,CAAC;AAC5G,OAAO,EACL,KAAK,UAAU,EAEf,KAAK,cAAc,EAMpB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,KAAK,aAAa,EAAqE,MAAM,cAAc,CAAC;AACrH,OAAO,EAAwB,KAAK,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAI1E,MAAM,WAAW,oBAAoB;IACnC;;;;;;OAMG;IACH,aAAa,CAAC,EAAE,aAAa,GAAG,CAAC,CAAC,GAAG,EAAE,cAAc,KAAK,aAAa,CAAC,CAAC;IACzE,wEAAwE;IACxE,MAAM,CAAC,EAAE,gBAAgB,CAAC;IAC1B,iEAAiE;IACjE,UAAU,CAAC,EAAE,UAAU,CAAC,cAAc,CAAC,EAAE,CAAC;CAC3C;AAED,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,CAAC,KAAK,EAAE,sBAAsB,EAAE,OAAO,EAAE,aAAa,KAAK,OAAO,CAAC,uBAAuB,CAAC,CAAC;IACrG,MAAM,EAAE,CAAC,KAAK,EAAE,sBAAsB,EAAE,OAAO,EAAE,aAAa,KAAK,OAAO,CAAC,uBAAuB,CAAC,CAAC;CACrG;AAED,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,oBAAyB,GAAG,aAAa,CA4CrF"}
1
+ {"version":3,"file":"session-routes.d.ts","sourceRoot":"","sources":["../../src/server/session-routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,OAAO,KAAK,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,YAAY,CAAC;AAC5G,OAAO,EACL,KAAK,UAAU,EAEf,KAAK,cAAc,EAMpB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,KAAK,aAAa,EAAqE,MAAM,cAAc,CAAC;AACrH,OAAO,EAAwB,KAAK,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG1E,OAAO,EAA8C,KAAK,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAElH,MAAM,WAAW,oBAAoB;IACnC;;;;;;OAMG;IACH,aAAa,CAAC,EAAE,aAAa,GAAG,CAAC,CAAC,GAAG,EAAE,cAAc,KAAK,aAAa,CAAC,CAAC;IACzE,wEAAwE;IACxE,MAAM,CAAC,EAAE,gBAAgB,CAAC;IAC1B,2DAA2D;IAC3D,UAAU,CAAC,EAAE,UAAU,CAAC,cAAc,CAAC,EAAE,CAAC;IAC1C;;;OAGG;IACH,SAAS,CAAC,EAAE,wBAAwB,CAAC;CACtC;AAED,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,CAAC,KAAK,EAAE,sBAAsB,EAAE,OAAO,EAAE,aAAa,KAAK,OAAO,CAAC,uBAAuB,CAAC,CAAC;IACrG,MAAM,EAAE,CAAC,KAAK,EAAE,sBAAsB,EAAE,OAAO,EAAE,aAAa,KAAK,OAAO,CAAC,uBAAuB,CAAC,CAAC;CACrG;AAED,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,oBAAyB,GAAG,aAAa,CA6CrF"}
@@ -3,6 +3,7 @@ import { buildClearSessionCookies, buildSessionCookies, readSessionCookies } fro
3
3
  import { loadAuthServerConfig } from './config.js';
4
4
  import { refreshSession } from './refresh.js';
5
5
  import { revokeRefreshToken } from './revoke.js';
6
+ import { AUTH_ROUTE_RATE_LIMITS, authRouteRateLimit } from './route-rate-limit.js';
6
7
  export function createSessionRoutes(options = {}) {
7
8
  const cookieOptionsFor = (ctx) => typeof options.cookieOptions === 'function' ? options.cookieOptions(ctx) : (options.cookieOptions ?? {});
8
9
  const configFor = () => options.config ?? loadAuthServerConfig();
@@ -26,11 +27,12 @@ export function createSessionRoutes(options = {}) {
26
27
  logError: false,
27
28
  }));
28
29
  }
29
- // `refreshToken: ''` → the refresh cookie is left as it is.
30
- for (const cookie of buildSessionCookies({ ...tokens, refreshToken: '' }, cookieOptions))
30
+ // A rotating client returns a new refresh token: it replaces the
31
+ // cookie. Otherwise (`''`) the refresh cookie is left as it is.
32
+ for (const cookie of buildSessionCookies(tokens, cookieOptions))
31
33
  setCookie(ctx, cookie);
32
34
  return { expiresIn: tokens.expiresIn };
33
- }, { status: 200, middleware });
35
+ }, { status: 200, middleware: [...authRouteRateLimit('refresh', options.rateLimit, AUTH_ROUTE_RATE_LIMITS.refresh), ...middleware] });
34
36
  const logout = handler(async (_body, ctx) => {
35
37
  const cookieOptions = cookieOptionsFor(ctx);
36
38
  const { refreshToken } = readSessionCookies(ctx.rawEvent, cookieOptions);
@@ -39,7 +41,7 @@ export function createSessionRoutes(options = {}) {
39
41
  for (const cookie of buildClearSessionCookies(cookieOptions))
40
42
  setCookie(ctx, cookie);
41
43
  return { success: true };
42
- }, { status: 200, middleware });
44
+ }, { status: 200, middleware: [...authRouteRateLimit('logout', options.rateLimit, AUTH_ROUTE_RATE_LIMITS.logout), ...middleware] });
43
45
  return { refresh, logout };
44
46
  }
45
47
  //# sourceMappingURL=session-routes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-routes.js","sourceRoot":"","sources":["../../src/server/session-routes.ts"],"names":[],"mappings":"AAwCA,OAAO,EAIL,iBAAiB,EACjB,aAAa,EACb,OAAO,EACP,SAAS,EACT,SAAS,GACV,MAAM,qBAAq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AAE,OAAO,CAAC,SAAS,EAAE,sBAAsB,CAAC,MAAM,CAAC,EAAE,GAAG,UAAU,CAAC,EAAE,CAChI,CAAC;IAEF,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;AAC7B,CAAC"}
@@ -1,14 +1,12 @@
1
1
  /**
2
2
  * Self-service user registration against a Cognito User Pool.
3
3
  *
4
- * Wraps the three-step pattern every consumer ends up writing for a
5
- * working "sign-up + immediate login" flow:
4
+ * Wraps the pattern every consumer ends up writing for a working
5
+ * "sign-up + immediate login" flow:
6
6
  *
7
7
  * 1. `SignUp` — create the user with email + password + standard
8
8
  * attributes.
9
- * 2. `AdminConfirmSignUp` — skip the email-verification challenge
10
- * (the consumer's own flow is responsible for whatever real
11
- * verification ships before / after this).
9
+ * 2. `AdminConfirmSignUp` — skip Cognito's email-verification challenge.
12
10
  * 3. `AdminUpdateUserAttributes` — flip `email_verified=true` so
13
11
  * Cognito doesn't re-challenge on the next sign-in, and apply
14
12
  * {@link SignUpInput.customAttributes}.
@@ -19,11 +17,22 @@
19
17
  * input, so a client that could write them would let any user promote
20
18
  * themselves). Admin APIs bypass client write permissions.
21
19
  *
22
- * Steps 2-3 are gated by {@link SignUpInput.autoConfirm} (default
23
- * `true`). When the consumer wants the standard Cognito email-link
24
- * verification, set it to `false` and call `AdminConfirmSignUp`
25
- * yourself out-of-band — custom attributes are then applied with a
26
- * standalone `AdminUpdateUserAttributes` right after `SignUp`.
20
+ * # Steps 2-3 are a security decision, so they have no default
21
+ *
22
+ * Confirming the account and marking its address verified asserts that
23
+ * the person signing up CONTROLS that address. If nothing proved it,
24
+ * anyone can register someone else's address as "verified" — and every
25
+ * flow that trusts a verified address (account linking on federated
26
+ * sign-in, invitations matched by e-mail, password reset by e-mail) then
27
+ * trusts the impostor. {@link SignUpInput.autoConfirm} is therefore
28
+ * required:
29
+ *
30
+ * - `true` — the CALLER has already proven ownership (a code it
31
+ * delivered and checked with `verifyVerificationCode`, an
32
+ * invitation token mailed to the address). Steps 2-3 run.
33
+ * - `false` — Cognito sends its own verification code and the account
34
+ * stays unconfirmed until it is entered; custom attributes are
35
+ * applied with a standalone `AdminUpdateUserAttributes`.
27
36
  *
28
37
  * In production the executing IAM principal needs
29
38
  * `cognito-idp:AdminConfirmSignUp` and
@@ -56,13 +65,17 @@ export interface SignUpInput {
56
65
  */
57
66
  customAttributes?: Record<string, string>;
58
67
  /**
59
- * When `true` (default), follow the SignUp with
60
- * `AdminConfirmSignUp` + `email_verified=true` so the user can
61
- * immediately sign in without going through Cognito's email
62
- * verification challenge. Set to `false` to opt into the standard
63
- * verification flow.
68
+ * REQUIRED — has the caller already proven the user controls `email`?
69
+ *
70
+ * - `true`: yes (a code it delivered and verified, an invitation
71
+ * token mailed to the address). The account is confirmed and
72
+ * `email_verified=true` at once, so the user can sign in right away.
73
+ * - `false`: no. Cognito sends its own verification code; the account
74
+ * stays unconfirmed until it is entered.
75
+ *
76
+ * There is deliberately no default — see the module docs.
64
77
  */
65
- autoConfirm?: boolean;
78
+ autoConfirm: boolean;
66
79
  /**
67
80
  * Forwarded verbatim as Cognito `ClientMetadata` on the `SignUp`
68
81
  * call, so the pool's Lambda triggers — notably a `CustomEmailSender`
@@ -86,7 +99,9 @@ export interface SignUpResult {
86
99
  * Errors are normalized via {@link mapProviderError}: a duplicate
87
100
  * email surfaces as `UsernameExistsException` (HTTP 401 by default —
88
101
  * route handlers typically map this to a 409), an invalid password
89
- * as `invalid_parameter` (HTTP 422).
102
+ * as `invalid_parameter` (HTTP 422). A call without an explicit
103
+ * {@link SignUpInput.autoConfirm} is a programming error and throws
104
+ * before Cognito is contacted.
90
105
  */
91
106
  export declare function signUpUser(input: SignUpInput, config?: AuthServerConfig): Promise<SignUpResult>;
92
107
  //# sourceMappingURL=sign-up.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sign-up.d.ts","sourceRoot":"","sources":["../../src/server/sign-up.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;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AAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC1C;;;;;;;;;;OAUG;IACH,WAAW,EAAE,OAAO,CAAC;IACrB;;;;;;;OAOG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACzC;AAED,MAAM,WAAW,YAAY;IAC3B,6DAA6D;IAC7D,OAAO,EAAE,MAAM,CAAC;IAChB,qDAAqD;IACrD,SAAS,EAAE,OAAO,CAAC;CACpB;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,UAAU,CAC9B,KAAK,EAAE,WAAW,EAClB,MAAM,GAAE,gBAAyC,GAChD,OAAO,CAAC,YAAY,CAAC,CA8FvB"}
@@ -1,14 +1,12 @@
1
1
  /**
2
2
  * Self-service user registration against a Cognito User Pool.
3
3
  *
4
- * Wraps the three-step pattern every consumer ends up writing for a
5
- * working "sign-up + immediate login" flow:
4
+ * Wraps the pattern every consumer ends up writing for a working
5
+ * "sign-up + immediate login" flow:
6
6
  *
7
7
  * 1. `SignUp` — create the user with email + password + standard
8
8
  * attributes.
9
- * 2. `AdminConfirmSignUp` — skip the email-verification challenge
10
- * (the consumer's own flow is responsible for whatever real
11
- * verification ships before / after this).
9
+ * 2. `AdminConfirmSignUp` — skip Cognito's email-verification challenge.
12
10
  * 3. `AdminUpdateUserAttributes` — flip `email_verified=true` so
13
11
  * Cognito doesn't re-challenge on the next sign-in, and apply
14
12
  * {@link SignUpInput.customAttributes}.
@@ -19,11 +17,22 @@
19
17
  * input, so a client that could write them would let any user promote
20
18
  * themselves). Admin APIs bypass client write permissions.
21
19
  *
22
- * Steps 2-3 are gated by {@link SignUpInput.autoConfirm} (default
23
- * `true`). When the consumer wants the standard Cognito email-link
24
- * verification, set it to `false` and call `AdminConfirmSignUp`
25
- * yourself out-of-band — custom attributes are then applied with a
26
- * standalone `AdminUpdateUserAttributes` right after `SignUp`.
20
+ * # Steps 2-3 are a security decision, so they have no default
21
+ *
22
+ * Confirming the account and marking its address verified asserts that
23
+ * the person signing up CONTROLS that address. If nothing proved it,
24
+ * anyone can register someone else's address as "verified" — and every
25
+ * flow that trusts a verified address (account linking on federated
26
+ * sign-in, invitations matched by e-mail, password reset by e-mail) then
27
+ * trusts the impostor. {@link SignUpInput.autoConfirm} is therefore
28
+ * required:
29
+ *
30
+ * - `true` — the CALLER has already proven ownership (a code it
31
+ * delivered and checked with `verifyVerificationCode`, an
32
+ * invitation token mailed to the address). Steps 2-3 run.
33
+ * - `false` — Cognito sends its own verification code and the account
34
+ * stays unconfirmed until it is entered; custom attributes are
35
+ * applied with a standalone `AdminUpdateUserAttributes`.
27
36
  *
28
37
  * In production the executing IAM principal needs
29
38
  * `cognito-idp:AdminConfirmSignUp` and
@@ -41,12 +50,21 @@ import { AuthError, mapProviderError } from './errors.js';
41
50
  * Errors are normalized via {@link mapProviderError}: a duplicate
42
51
  * email surfaces as `UsernameExistsException` (HTTP 401 by default —
43
52
  * route handlers typically map this to a 409), an invalid password
44
- * as `invalid_parameter` (HTTP 422).
53
+ * as `invalid_parameter` (HTTP 422). A call without an explicit
54
+ * {@link SignUpInput.autoConfirm} is a programming error and throws
55
+ * before Cognito is contacted.
45
56
  */
46
57
  export async function signUpUser(input, config = loadAuthServerConfig()) {
58
+ // Enforced at runtime too: JavaScript callers, `as` casts and spread
59
+ // objects all slip past the type, and the silent fallback this replaces
60
+ // (`true`) marked unproven addresses as verified.
61
+ if (typeof input.autoConfirm !== 'boolean') {
62
+ throw new AuthError('auto_confirm_required', 'signUpUser: `autoConfirm` must be set explicitly — `true` only when your flow has already proven ' +
63
+ 'the user controls the address (e.g. verifyVerificationCode), `false` to let Cognito verify it.', 500);
64
+ }
47
65
  const client = getCognitoClient(config.region, config.endpoint);
48
66
  const email = input.email.toLowerCase();
49
- const autoConfirm = input.autoConfirm ?? true;
67
+ const autoConfirm = input.autoConfirm;
50
68
  const userAttributes = buildStandardAttributes(email, input);
51
69
  const customAttributes = buildCustomAttributes(input);
52
70
  let userSub;
@@ -1 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AAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,uFAAuF;AACvF,SAAS,qBAAqB,CAAC,KAAkB;IAC/C,OAAO,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,gBAAgB,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;QAC1E,IAAI,EAAE,UAAU,IAAI,EAAE;QACtB,KAAK,EAAE,KAAK;KACb,CAAC,CAAC,CAAC;AACN,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../../../src/server/store/postgres.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAS,KAAK,OAAO,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,KAAK,EAEV,qBAAqB,EACtB,MAAM,oBAAoB,CAAC;AAgD5B;;;;;;GAMG;AACH,wBAAgB,mCAAmC,CACjD,CAAC,GAAE,OAAe,GACjB,qBAAqB,CAiEvB"}
1
+ {"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../../../src/server/store/postgres.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAS,KAAK,OAAO,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,KAAK,EAEV,qBAAqB,EACtB,MAAM,oBAAoB,CAAC;AAmE5B;;;;;;GAMG;AACH,wBAAgB,mCAAmC,CACjD,CAAC,GAAE,OAAe,GACjB,qBAAqB,CAqEvB"}
@@ -25,6 +25,11 @@
25
25
  import { query } from '@venturekit/data';
26
26
  /** Mapper options pinning the raw `snake_case` row shape for this store's reads. */
27
27
  const RAW_ROWS = { camelCase: false };
28
+ /** Every column a record needs, epochs in ms. */
29
+ const RECORD_COLUMNS = `channel, identifier, code_hash,
30
+ (EXTRACT(EPOCH FROM expires_at) * 1000)::bigint AS expires_at,
31
+ attempts, max_attempts, issued_count,
32
+ (EXTRACT(EPOCH FROM window_ends_at) * 1000)::bigint AS window_ends_at`;
28
33
  function rowToRecord(r) {
29
34
  const codeHash = r.code_hash ?? r.codeHash;
30
35
  const expiresAt = r.expires_at ?? r.expiresAt;
@@ -40,8 +45,15 @@ function rowToRecord(r) {
40
45
  expiresAt: Number(expiresAt),
41
46
  attempts: r.attempts,
42
47
  maxAttempts,
48
+ issuedCount: r.issued_count ?? r.issuedCount ?? 1,
49
+ // A pre-window row counts as a window already over.
50
+ windowEndsAt: Number(r.window_ends_at ?? r.windowEndsAt ?? 0),
43
51
  };
44
52
  }
53
+ const firstRecord = (rows) => {
54
+ const r = rows[0];
55
+ return r ? rowToRecord(r) : undefined;
56
+ };
45
57
  /**
46
58
  * Build a Postgres-backed {@link VerificationCodeStore} bound to `q`.
47
59
  *
@@ -51,43 +63,47 @@ function rowToRecord(r) {
51
63
  */
52
64
  export function createPostgresVerificationCodeStore(q = query) {
53
65
  return {
54
- async put({ channel, identifier, codeHash, expiresAt, maxAttempts }) {
55
- // Opportunistic sweep of already-expired rows on every write —
56
- // keeps the table bounded without a dedicated cron (the migration
57
- // ships the `expires_at` index that backs this).
58
- await q(`DELETE FROM vk_verification_codes WHERE expires_at < CURRENT_TIMESTAMP`);
59
- // Idempotent per the store contract: a re-request overwrites the
60
- // outstanding code for this (channel, identifier) and resets the
61
- // attempt counter — a fresh code means "let me try again", not
62
- // "reset the limit on the old one".
66
+ async put({ channel, identifier, codeHash, expiresAt, maxAttempts, issuedCount, windowEndsAt }) {
67
+ // Opportunistic sweep on every write keeps the table bounded without
68
+ // a dedicated cron. Only rows whose code AND issuance window are both
69
+ // over: dropping a row with a live window would reset its code count.
70
+ await q(`DELETE FROM vk_verification_codes
71
+ WHERE expires_at < CURRENT_TIMESTAMP
72
+ AND (window_ends_at IS NULL OR window_ends_at < CURRENT_TIMESTAMP)`);
73
+ // A new code replaces the outstanding one with a fresh attempt
74
+ // budget; the window counters are the helper's to compute.
63
75
  await q(`INSERT INTO vk_verification_codes
64
- (channel, identifier, code_hash, expires_at, attempts, max_attempts)
65
- VALUES ($1, $2, $3, to_timestamp($4 / 1000.0), 0, $5)
76
+ (channel, identifier, code_hash, expires_at, attempts, max_attempts, issued_count, window_ends_at)
77
+ VALUES ($1, $2, $3, to_timestamp($4 / 1000.0), 0, $5, $6, to_timestamp($7 / 1000.0))
66
78
  ON CONFLICT (channel, identifier) DO UPDATE
67
- SET code_hash = EXCLUDED.code_hash,
68
- expires_at = EXCLUDED.expires_at,
69
- attempts = 0,
70
- max_attempts = EXCLUDED.max_attempts,
71
- created_at = NOW()`, [channel, identifier, codeHash, expiresAt, maxAttempts]);
79
+ SET code_hash = EXCLUDED.code_hash,
80
+ expires_at = EXCLUDED.expires_at,
81
+ attempts = 0,
82
+ max_attempts = EXCLUDED.max_attempts,
83
+ issued_count = EXCLUDED.issued_count,
84
+ window_ends_at = EXCLUDED.window_ends_at,
85
+ created_at = NOW()`, [channel, identifier, codeHash, expiresAt, maxAttempts, issuedCount, windowEndsAt]);
72
86
  },
73
87
  async get({ channel, identifier }) {
74
- // Return the row as-is, INCLUDING when expired — verifyVerificationCode
75
- // performs the expiry check and deletes the row itself.
76
- return q(`SELECT channel, identifier, code_hash,
77
- (EXTRACT(EPOCH FROM expires_at) * 1000)::bigint AS expires_at,
78
- attempts, max_attempts
88
+ // The row as-is, INCLUDING when expired or exhausted.
89
+ return q(`SELECT ${RECORD_COLUMNS}
79
90
  FROM vk_verification_codes
80
91
  WHERE channel = $1 AND identifier = $2
81
- LIMIT 1`, [channel, identifier], (rows) => {
82
- const r = rows[0];
83
- return r ? rowToRecord(r) : undefined;
84
- }, RAW_ROWS);
92
+ LIMIT 1`, [channel, identifier], firstRecord, RAW_ROWS);
85
93
  },
86
- async incrementAttempts({ channel, identifier }) {
94
+ async claimAttempt({ channel, identifier, now }) {
95
+ // One conditional UPDATE: the row lock serializes concurrent
96
+ // guesses, so at most `max_attempts` of them ever pass. RETURNING
97
+ // reports the attempt count as it was before this guess.
87
98
  return q(`UPDATE vk_verification_codes
88
99
  SET attempts = attempts + 1
89
100
  WHERE channel = $1 AND identifier = $2
90
- RETURNING attempts`, [channel, identifier], (rows) => rows[0]?.attempts ?? 0);
101
+ AND attempts < max_attempts
102
+ AND expires_at > to_timestamp($3 / 1000.0)
103
+ RETURNING channel, identifier, code_hash,
104
+ (EXTRACT(EPOCH FROM expires_at) * 1000)::bigint AS expires_at,
105
+ attempts - 1 AS attempts, max_attempts, issued_count,
106
+ (EXTRACT(EPOCH FROM window_ends_at) * 1000)::bigint AS window_ends_at`, [channel, identifier, now], firstRecord, RAW_ROWS);
91
107
  },
92
108
  async delete({ channel, identifier }) {
93
109
  await q(`DELETE FROM vk_verification_codes WHERE channel = $1 AND identifier = $2`, [channel, identifier]);
@@ -1 +1 @@
1
- {"version":3,"file":"postgres.js","sourceRoot":"","sources":["../../../src/server/store/postgres.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,KAAK,EAAgB,MAAM,kBAAkB,CAAC;AA6BvD,oFAAoF;AACpF,MAAM,QAAQ,GAAG,EAAE,SAAS,EAAE,KAAK,EAAW,CAAC;AAE/C,SAAS,WAAW,CAAC,CAAsB;IACzC,MAAM,QAAQ,GAAG,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,QAAQ,CAAC;IAC3C,MAAM,SAAS,GAAG,CAAC,CAAC,UAAU,IAAI,CAAC,CAAC,SAAS,CAAC;IAC9C,MAAM,WAAW,GAAG,CAAC,CAAC,YAAY,IAAI,CAAC,CAAC,WAAW,CAAC;IACpD,IAAI,QAAQ,KAAK,SAAS,IAAI,SAAS,KAAK,SAAS,IAAI,WAAW,KAAK,SAAS,EAAE,CAAC;QACnF,MAAM,IAAI,KAAK,CACb,mFAAmF;YACjF,2EAA2E,CAC9E,CAAC;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