@atproto/oauth-provider 0.25.6 → 0.27.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.
Files changed (105) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/dist/account/account-manager.d.ts +5 -11
  3. package/dist/account/account-manager.d.ts.map +1 -1
  4. package/dist/account/account-manager.js +17 -59
  5. package/dist/account/account-manager.js.map +1 -1
  6. package/dist/account/account-store.d.ts +2 -8
  7. package/dist/account/account-store.d.ts.map +1 -1
  8. package/dist/account/account-store.js.map +1 -1
  9. package/dist/errors/captcha-rejected-error.d.ts +12 -0
  10. package/dist/errors/captcha-rejected-error.d.ts.map +1 -0
  11. package/dist/errors/captcha-rejected-error.js +18 -0
  12. package/dist/errors/captcha-rejected-error.js.map +1 -0
  13. package/dist/errors/captcha-required-error.d.ts +9 -0
  14. package/dist/errors/captcha-required-error.d.ts.map +1 -0
  15. package/dist/errors/captcha-required-error.js +11 -0
  16. package/dist/errors/captcha-required-error.js.map +1 -0
  17. package/dist/errors/oauth-error.d.ts +1 -0
  18. package/dist/errors/oauth-error.d.ts.map +1 -1
  19. package/dist/errors/oauth-error.js +3 -0
  20. package/dist/errors/oauth-error.js.map +1 -1
  21. package/dist/errors/rate-limit-exceeded-error.d.ts +12 -0
  22. package/dist/errors/rate-limit-exceeded-error.d.ts.map +1 -0
  23. package/dist/errors/rate-limit-exceeded-error.js +14 -0
  24. package/dist/errors/rate-limit-exceeded-error.js.map +1 -0
  25. package/dist/errors/www-authenticate-error.d.ts +1 -0
  26. package/dist/errors/www-authenticate-error.d.ts.map +1 -1
  27. package/dist/errors/www-authenticate-error.js +4 -0
  28. package/dist/errors/www-authenticate-error.js.map +1 -1
  29. package/dist/hcaptcha/hcaptcha-client-tokens.d.ts +7 -0
  30. package/dist/hcaptcha/hcaptcha-client-tokens.d.ts.map +1 -0
  31. package/dist/hcaptcha/hcaptcha-client-tokens.js +2 -0
  32. package/dist/hcaptcha/hcaptcha-client-tokens.js.map +1 -0
  33. package/dist/hcaptcha/hcaptcha-manager.d.ts +23 -0
  34. package/dist/hcaptcha/hcaptcha-manager.d.ts.map +1 -0
  35. package/dist/hcaptcha/hcaptcha-manager.js +83 -0
  36. package/dist/hcaptcha/hcaptcha-manager.js.map +1 -0
  37. package/dist/hcaptcha/hcaptcha-verify-data.d.ts +15 -0
  38. package/dist/hcaptcha/hcaptcha-verify-data.d.ts.map +1 -0
  39. package/dist/hcaptcha/hcaptcha-verify-data.js +2 -0
  40. package/dist/hcaptcha/hcaptcha-verify-data.js.map +1 -0
  41. package/dist/lib/hcaptcha.d.ts +5 -11
  42. package/dist/lib/hcaptcha.d.ts.map +1 -1
  43. package/dist/lib/hcaptcha.js +12 -20
  44. package/dist/lib/hcaptcha.js.map +1 -1
  45. package/dist/lib/http/response.d.ts +1 -1
  46. package/dist/lib/http/response.d.ts.map +1 -1
  47. package/dist/lib/http/response.js +15 -17
  48. package/dist/lib/http/response.js.map +1 -1
  49. package/dist/lib/identifier.d.ts +3 -0
  50. package/dist/lib/identifier.d.ts.map +1 -0
  51. package/dist/lib/identifier.js +4 -0
  52. package/dist/lib/identifier.js.map +1 -0
  53. package/dist/lib/redis.d.ts.map +1 -1
  54. package/dist/lib/redis.js +7 -1
  55. package/dist/lib/redis.js.map +1 -1
  56. package/dist/oauth-errors.d.ts +3 -0
  57. package/dist/oauth-errors.d.ts.map +1 -1
  58. package/dist/oauth-errors.js +3 -0
  59. package/dist/oauth-errors.js.map +1 -1
  60. package/dist/oauth-hooks.d.ts +16 -14
  61. package/dist/oauth-hooks.d.ts.map +1 -1
  62. package/dist/oauth-hooks.js.map +1 -1
  63. package/dist/oauth-provider.d.ts +26 -7
  64. package/dist/oauth-provider.d.ts.map +1 -1
  65. package/dist/oauth-provider.js +28 -48
  66. package/dist/oauth-provider.js.map +1 -1
  67. package/dist/rate-limit/rate-limit-manager.d.ts +39 -0
  68. package/dist/rate-limit/rate-limit-manager.d.ts.map +1 -0
  69. package/dist/rate-limit/rate-limit-manager.js +99 -0
  70. package/dist/rate-limit/rate-limit-manager.js.map +1 -0
  71. package/dist/rate-limit/rate-limit-policies.d.ts +108 -0
  72. package/dist/rate-limit/rate-limit-policies.d.ts.map +1 -0
  73. package/dist/rate-limit/rate-limit-policies.js +90 -0
  74. package/dist/rate-limit/rate-limit-policies.js.map +1 -0
  75. package/dist/rate-limit/rate-limiter.d.ts +36 -0
  76. package/dist/rate-limit/rate-limiter.d.ts.map +1 -0
  77. package/dist/rate-limit/rate-limiter.js +2 -0
  78. package/dist/rate-limit/rate-limiter.js.map +1 -0
  79. package/dist/router/assets/send-error-page.d.ts.map +1 -1
  80. package/dist/router/assets/send-error-page.js +3 -2
  81. package/dist/router/assets/send-error-page.js.map +1 -1
  82. package/dist/router/create-api-middleware.d.ts.map +1 -1
  83. package/dist/router/create-api-middleware.js +72 -15
  84. package/dist/router/create-api-middleware.js.map +1 -1
  85. package/dist/router/create-authorization-page-middleware.d.ts.map +1 -1
  86. package/dist/router/create-authorization-page-middleware.js +18 -17
  87. package/dist/router/create-authorization-page-middleware.js.map +1 -1
  88. package/dist/router/create-oauth-middleware.d.ts.map +1 -1
  89. package/dist/router/create-oauth-middleware.js +9 -8
  90. package/dist/router/create-oauth-middleware.js.map +1 -1
  91. package/dist/types/email.d.ts +2 -1
  92. package/dist/types/email.d.ts.map +1 -1
  93. package/dist/types/email.js.map +1 -1
  94. package/dist/types/indentifier.d.ts +2 -3
  95. package/dist/types/indentifier.d.ts.map +1 -1
  96. package/dist/types/indentifier.js.map +1 -1
  97. package/package.json +17 -17
  98. package/dist/account/sign-in-data.d.ts +0 -22
  99. package/dist/account/sign-in-data.d.ts.map +0 -1
  100. package/dist/account/sign-in-data.js +0 -15
  101. package/dist/account/sign-in-data.js.map +0 -1
  102. package/dist/account/sign-up-input.d.ts +0 -28
  103. package/dist/account/sign-up-input.d.ts.map +0 -1
  104. package/dist/account/sign-up-input.js +0 -19
  105. package/dist/account/sign-up-input.js.map +0 -1
@@ -0,0 +1,108 @@
1
+ import type { ClientAuth } from '../client/client-auth.js';
2
+ import type { Client } from '../client/client.js';
3
+ import type { DeviceId } from '../device/device-id.js';
4
+ import type { HcaptchaVerifyData } from '../hcaptcha/hcaptcha-manager.js';
5
+ import type { RequestMetadata } from '../lib/http/request.js';
6
+ import type { RateLimiterFactory } from './rate-limiter.js';
7
+ declare const RATE_LIMIT_DEVICE_POLICIES: readonly ["sign-in", "sign-up", "reset-password-request", "reset-password-confirm"];
8
+ export declare const isRateLimitDevicePolicyName: (policy: string) => policy is RateLimitDevicePolicyName;
9
+ export type RateLimitDevicePolicyName = (typeof RATE_LIMIT_DEVICE_POLICIES)[number];
10
+ /**
11
+ * The context of the account routes, whose requests carry the form input
12
+ * (including the hCaptcha token, if any).
13
+ */
14
+ export type RateLimitDeviceContext = {
15
+ kind: 'device';
16
+ deviceId: DeviceId;
17
+ deviceMetadata: RequestMetadata;
18
+ data: HcaptchaVerifyData;
19
+ };
20
+ export type RateLimitClientPolicyName = 'pushed-authorization-request';
21
+ /**
22
+ * The context of the OAuth client requests, which cannot carry an hCaptcha
23
+ * token.
24
+ */
25
+ export type RateLimitClientContext = {
26
+ kind: 'client';
27
+ deviceMetadata: RequestMetadata;
28
+ client: Client;
29
+ clientAuth: ClientAuth;
30
+ };
31
+ /**
32
+ * Maps each rate limit policy to the context it provides to its rules'
33
+ * {@link RateLimitRule.key}.
34
+ */
35
+ export type RateLimitPolicyContexts = {
36
+ [K in RateLimitDevicePolicyName]: RateLimitDeviceContext;
37
+ } & {
38
+ [K in RateLimitClientPolicyName]: RateLimitClientContext;
39
+ };
40
+ export type RateLimitPolicyName = RateLimitDevicePolicyName | RateLimitClientPolicyName;
41
+ export type RateLimitContext = RateLimitDeviceContext | RateLimitClientContext;
42
+ /**
43
+ * @returns the key to count the request under, or `null` for the rule not to
44
+ * apply to the request.
45
+ */
46
+ export type RateLimitKeyGetter<C extends RateLimitContext = RateLimitContext> = (ctx: C) => string | null;
47
+ export declare const ipKey: RateLimitKeyGetter;
48
+ export declare const identifierKey: RateLimitKeyGetter<RateLimitDeviceContext>;
49
+ export declare const identifierIpKey: RateLimitKeyGetter<RateLimitDeviceContext>;
50
+ /**
51
+ * The client ID, for clients that authenticated themselves (`null` for public
52
+ * clients).
53
+ */
54
+ export declare const authenticatedClientKey: RateLimitKeyGetter<RateLimitClientContext>;
55
+ /**
56
+ * The client ID and the IP address, for public clients (`null` for clients
57
+ * that authenticated themselves). Since anyone can claim to be a public client,
58
+ * keying on the IP address prevents anyone from exhausting a public client's
59
+ * budget.
60
+ */
61
+ export declare const publicClientIpKey: RateLimitKeyGetter<RateLimitClientContext>;
62
+ /**
63
+ * @note A rule's limiter is named after the rule's position in its tier and
64
+ * its `durationMs`. Reordering the rules of a tier between deploys may cause
65
+ * rules with the same window to swap counters, until those expire.
66
+ * @note A rule with no `points` is exceeded by every request. Since it needs no
67
+ * storage, it is not backed by the {@link RateLimitsOptions.factory}, and
68
+ * applies even when no rate limits are configured.
69
+ */
70
+ export type RateLimitRule<C extends RateLimitContext = RateLimitContext> = {
71
+ key: RateLimitKeyGetter<C>;
72
+ points: number;
73
+ durationMs: number;
74
+ };
75
+ export interface RateLimitPolicy<C extends RateLimitContext = RateLimitContext> {
76
+ /**
77
+ * Exceeding any of these rules rejects the request with a
78
+ * `rate_limit_exceeded` (HTTP 429) error.
79
+ *
80
+ * @note Never key a rule on the identifier alone here (e.g. using
81
+ * {@link identifierKey}), as that would allow anyone to lock a victim out of
82
+ * their account.
83
+ */
84
+ block: readonly RateLimitRule<C>[];
85
+ }
86
+ export interface RateLimitDevicePolicy<C extends RateLimitDeviceContext = RateLimitDeviceContext> extends RateLimitPolicy<C> {
87
+ /**
88
+ * Exceeding any of these rules requires the request to carry a valid hCaptcha
89
+ * token. Ignored when hCaptcha is not configured.
90
+ */
91
+ captcha: readonly RateLimitRule<C>[];
92
+ }
93
+ export type RateLimitPolicies = {
94
+ readonly [P in RateLimitPolicyName]: P extends RateLimitDevicePolicyName ? RateLimitDevicePolicy<RateLimitPolicyContexts[P]> : RateLimitPolicy<RateLimitPolicyContexts[P]>;
95
+ };
96
+ export declare const DEFAULT_RATE_LIMIT_POLICIES: RateLimitPolicies;
97
+ export type RateLimitsOptions = {
98
+ factory: RateLimiterFactory;
99
+ /**
100
+ * Overrides {@link DEFAULT_RATE_LIMIT_POLICIES}. Each tier provided replaces
101
+ * the corresponding default tier's rules entirely.
102
+ */
103
+ policies?: {
104
+ readonly [P in RateLimitPolicyName]?: Partial<RateLimitPolicies[P]>;
105
+ };
106
+ };
107
+ export {};
108
+ //# sourceMappingURL=rate-limit-policies.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limit-policies.d.ts","sourceRoot":"","sources":["../../src/rate-limit/rate-limit-policies.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAA;AAC1D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AACjD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAA;AACtD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAA;AACzE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AAE7D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AAE3D,QAAA,MAAM,0BAA0B,qFAKrB,CAAA;AAEX,eAAO,MAAM,2BAA2B,WAC9B,MAAM,KACb,MAAM,IAAI,yBAEZ,CAAA;AAED,MAAM,MAAM,yBAAyB,GACnC,CAAC,OAAO,0BAA0B,CAAC,CAAC,MAAM,CAAC,CAAA;AAE7C;;;GAGG;AACH,MAAM,MAAM,sBAAsB,GAAG;IACnC,IAAI,EAAE,QAAQ,CAAA;IACd,QAAQ,EAAE,QAAQ,CAAA;IAClB,cAAc,EAAE,eAAe,CAAA;IAC/B,IAAI,EAAE,kBAAkB,CAAA;CACzB,CA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AC,SAAS,gBAAgB,GAAG,gBAAgB;IAE7C;;;;;;;OAOG;IACH,KAAK,EAAE,SAAS,aAAa,CAAC,CAAC,CAAC,EAAE,CAAA;CACnC;AAED,MAAM,WAAW,qBAAqB,CACpC,CAAC,SAAS,sBAAsB,GAAG,sBAAsB,CACzD,SAAQ,eAAe,CAAC,CAAC,CAAC;IAC1B;;;OAGG;IACH,OAAO,EAAE,SAAS,aAAa,CAAC,CAAC,CAAC,EAAE,CAAA;CACrC;AAED,MAAM,MAAM,iBAAiB,GAAG;IAC9B,QAAQ,EAAE,CAAC,IAAI,mBAAmB,GAAG,CAAC,SAAS,yBAAyB,GACpE,qBAAqB,CAAC,uBAAuB,CAAC,CAAC,CAAC,CAAC,GACjD,eAAe,CAAC,uBAAuB,CAAC,CAAC,CAAC,CAAC;CAChD,CAAA;AAED,eAAO,MAAM,2BAA2B,EAAE,iBA2CzC,CAAA;AAED,MAAM,MAAM,iBAAiB,GAAG;IAC9B,OAAO,EAAE,kBAAkB,CAAA;IAE3B;;;OAGG;IACH,QAAQ,CAAC,EAAE;QACT,QAAQ,EAAE,CAAC,IAAI,mBAAmB,CAAC,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC;KACpE,CAAA;CACF,CAAA"}
@@ -0,0 +1,90 @@
1
+ import { DAY, HOUR, MINUTE } from '@atproto/common';
2
+ import { normalizeIdentifierString } from '../lib/identifier.js';
3
+ const RATE_LIMIT_DEVICE_POLICIES = Object.freeze([
4
+ 'sign-in',
5
+ 'sign-up',
6
+ 'reset-password-request',
7
+ 'reset-password-confirm',
8
+ ]);
9
+ export const isRateLimitDevicePolicyName = (policy) => {
10
+ return RATE_LIMIT_DEVICE_POLICIES.includes(policy);
11
+ };
12
+ export const ipKey = (ctx) => ctx.deviceMetadata.ipAddress;
13
+ // @NOTE The identifier (an email address or a handle, also part of the
14
+ // `identifierIpKey`) is stored in plain text by the rate limiter backend (e.g.
15
+ // in Redis). Backends that must not hold PII should hash the keys they
16
+ // receive (e.g. with an HMAC, as a plain hash of an email address can be
17
+ // reversed by guessing).
18
+ export const identifierKey = (ctx) => {
19
+ const identifier = ctx.data.action === 'sign-up'
20
+ ? ctx.data.input.handle
21
+ : 'identifier' in ctx.data.input
22
+ ? ctx.data.input.identifier
23
+ : undefined;
24
+ return identifier ? normalizeIdentifierString(identifier) : null;
25
+ };
26
+ export const identifierIpKey = (ctx) => {
27
+ const identifier = identifierKey(ctx);
28
+ // @NOTE IP addresses never contain spaces, making this unambiguous
29
+ return identifier ? `${identifier} ${ctx.deviceMetadata.ipAddress}` : null;
30
+ };
31
+ /**
32
+ * The client ID, for clients that authenticated themselves (`null` for public
33
+ * clients).
34
+ */
35
+ export const authenticatedClientKey = (ctx) => (ctx.clientAuth.method !== 'none' ? ctx.client.id : null);
36
+ /**
37
+ * The client ID and the IP address, for public clients (`null` for clients
38
+ * that authenticated themselves). Since anyone can claim to be a public client,
39
+ * keying on the IP address prevents anyone from exhausting a public client's
40
+ * budget.
41
+ */
42
+ export const publicClientIpKey = (ctx) => ctx.clientAuth.method === 'none'
43
+ ? // @NOTE Client IDs (URLs) never contain spaces
44
+ `${ctx.client.id} ${ctx.deviceMetadata.ipAddress}`
45
+ : null;
46
+ export const DEFAULT_RATE_LIMIT_POLICIES = {
47
+ 'sign-in': {
48
+ captcha: [
49
+ { key: identifierKey, points: 5, durationMs: 15 * MINUTE },
50
+ { key: ipKey, points: 20, durationMs: 15 * MINUTE },
51
+ ],
52
+ block: [
53
+ { key: identifierIpKey, points: 25, durationMs: 5 * MINUTE },
54
+ { key: identifierIpKey, points: 50, durationMs: DAY },
55
+ { key: ipKey, points: 100, durationMs: 5 * MINUTE },
56
+ ],
57
+ },
58
+ 'sign-up': {
59
+ // @NOTE No points: every sign-up requires a captcha
60
+ captcha: [{ key: ipKey, points: 0, durationMs: 0 }],
61
+ block: [
62
+ { key: ipKey, points: 20, durationMs: HOUR },
63
+ { key: ipKey, points: 100, durationMs: DAY },
64
+ ],
65
+ },
66
+ 'reset-password-request': {
67
+ captcha: [
68
+ { key: identifierKey, points: 3, durationMs: HOUR },
69
+ { key: ipKey, points: 5, durationMs: HOUR },
70
+ ],
71
+ block: [
72
+ { key: ipKey, points: 15, durationMs: HOUR },
73
+ { key: ipKey, points: 50, durationMs: DAY },
74
+ ],
75
+ },
76
+ 'reset-password-confirm': {
77
+ captcha: [{ key: ipKey, points: 5, durationMs: 15 * MINUTE }],
78
+ block: [{ key: ipKey, points: 50, durationMs: 5 * MINUTE }],
79
+ },
80
+ 'pushed-authorization-request': {
81
+ block: [
82
+ // @NOTE Shared by all the users of the client, hence the higher limit
83
+ { key: authenticatedClientKey, points: 3000, durationMs: 5 * MINUTE },
84
+ // @NOTE Unauthenticated clients are typically not running on a server
85
+ // and are initiating requests from devices with dynamic IPs.
86
+ { key: publicClientIpKey, points: 50, durationMs: 5 * MINUTE },
87
+ ],
88
+ },
89
+ };
90
+ //# sourceMappingURL=rate-limit-policies.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limit-policies.js","sourceRoot":"","sources":["../../src/rate-limit/rate-limit-policies.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAMnD,OAAO,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAA;AAGhE,MAAM,0BAA0B,GAAG,MAAM,CAAC,MAAM,CAAC;IAC/C,SAAS;IACT,SAAS;IACT,wBAAwB;IACxB,wBAAwB;CAChB,CAAC,CAAA;AAEX,MAAM,CAAC,MAAM,2BAA2B,GAAG,CACzC,MAAc,EACuB,EAAE;IACvC,OAAQ,0BAAgD,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAA;AAC3E,CAAC,CAAA;AAkDD,MAAM,CAAC,MAAM,KAAK,GAAuB,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,cAAc,CAAC,SAAS,CAAA;AAE9E,uEAAuE;AACvE,+E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E,IAAI,EAAE;YAC5C,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,UAAU,EAAE,GAAG,EAAE;SAC5C;KACF;IACD,wBAAwB,EAAE;QACxB,OAAO,EAAE,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,EAAE,UAAU,EAAE,EAAE,GAAG,MAAM,EAAE,CAAC;QAC7D,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,EAAE,UAAU,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC;KAC5D;IACD,8BAA8B,EAAE;QAC9B,KAAK,EAAE;YACL,sEAAsE;YACtE,EAAE,GAAG,EAAE,sBAAsB,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,GAAG,MAAM,EAAE;YACrE,sEAAsE;YACtE,6DAA6D;YAC7D,EAAE,GAAG,EAAE,iBAAiB,EAAE,MAAM,EAAE,EAAE,EAAE,UAAU,EAAE,CAAC,GAAG,MAAM,EAAE;SAC/D;KACF;CACF,CAAA","sourcesContent":["import { DAY, HOUR, MINUTE } from '@atproto/common'\nimport type { ClientAuth } from '../client/client-auth.js'\nimport type { Client } from '../client/client.js'\nimport type { DeviceId } from '../device/device-id.js'\nimport type { HcaptchaVerifyData } from '../hcaptcha/hcaptcha-manager.js'\nimport type { RequestMetadata } from '../lib/http/request.js'\nimport { normalizeIdentifierString } from '../lib/identifier.js'\nimport type { RateLimiterFactory } from './rate-limiter.js'\n\nconst RATE_LIMIT_DEVICE_POLICIES = Object.freeze([\n 'sign-in',\n 'sign-up',\n 'reset-password-request',\n 'reset-password-confirm',\n] as const)\n\nexport const isRateLimitDevicePolicyName = (\n policy: string,\n): policy is RateLimitDevicePolicyName => {\n return (RATE_LIMIT_DEVICE_POLICIES as readonly string[]).includes(policy)\n}\n\nexport type RateLimitDevicePolicyName =\n (typeof RATE_LIMIT_DEVICE_POLICIES)[number]\n\n/**\n * The context of the account routes, whose requests carry the form input\n * (including the hCaptcha token, if any).\n */\nexport type RateLimitDeviceContext = {\n kind: 'device'\n deviceId: DeviceId\n deviceMetadata: RequestMetadata\n data: HcaptchaVerifyData\n}\n\nexport type RateLimitClientPolicyName = 'pushed-authorization-request'\n\n/**\n * The context of the OAuth client requests, which cannot carry an hCaptcha\n * token.\n */\nexport type RateLimitClientContext = {\n kind: 'client'\n deviceMetadata: RequestMetadata\n client: Client\n clientAuth: ClientAuth\n}\n\n/**\n * Maps each rate limit policy to the context it provides to its rules'\n * {@link RateLimitRule.key}.\n */\nexport type RateLimitPolicyContexts = {\n [K in RateLimitDevicePolicyName]: RateLimitDeviceContext\n} & {\n [K in RateLimitClientPolicyName]: RateLimitClientContext\n}\n\nexport type RateLimitPolicyName =\n RateLimitDevicePolicyName | RateLimitClientPolicyName\nexport type RateLimitContext = RateLimitDeviceContext | RateLimitClientContext\n\n/**\n * @returns the key to count the request under, or `null` for the rule not to\n * apply to the request.\n */\nexport type RateLimitKeyGetter<C extends RateLimitContext = RateLimitContext> =\n (ctx: C) => string | null\n\nexport const ipKey: RateLimitKeyGetter = (ctx) => ctx.deviceMetadata.ipAddress\n\n// @NOTE The identifier (an email address or a handle, also part of the\n// `identifierIpKey`) is stored in plain text by the rate limiter backend (e.g.\n// in Redis). Backends that must not hold PII should hash the keys they\n// receive (e.g. with an HMAC, as a plain hash of an email address can be\n// reversed by guessing).\nexport const identifierKey: RateLimitKeyGetter<RateLimitDeviceContext> = (\n ctx,\n) => {\n const identifier =\n ctx.data.action === 'sign-up'\n ? ctx.data.input.handle\n : 'identifier' in ctx.data.input\n ? ctx.data.input.identifier\n : undefined\n return identifier ? normalizeIdentifierString(identifier) : null\n}\n\nexport const identifierIpKey: RateLimitKeyGetter<RateLimitDeviceContext> = (\n ctx,\n) => {\n const identifier = identifierKey(ctx)\n // @NOTE IP addresses never contain spaces, making this unambiguous\n return identifier ? `${identifier} ${ctx.deviceMetadata.ipAddress}` : null\n}\n\n/**\n * The client ID, for clients that authenticated themselves (`null` for public\n * clients).\n */\nexport const authenticatedClientKey: RateLimitKeyGetter<\n RateLimitClientContext\n> = (ctx) => (ctx.clientAuth.method !== 'none' ? ctx.client.id : null)\n\n/**\n * The client ID and the IP address, for public clients (`null` for clients\n * that authenticated themselves). Since anyone can claim to be a public client,\n * keying on the IP address prevents anyone from exhausting a public client's\n * budget.\n */\nexport const publicClientIpKey: RateLimitKeyGetter<RateLimitClientContext> = (\n ctx,\n) =>\n ctx.clientAuth.method === 'none'\n ? // @NOTE Client IDs (URLs) never contain spaces\n `${ctx.client.id} ${ctx.deviceMetadata.ipAddress}`\n : null\n\n/**\n * @note A rule's limiter is named after the rule's position in its tier and\n * its `durationMs`. Reordering the rules of a tier between deploys may cause\n * rules with the same window to swap counters, until those expire.\n * @note A rule with no `points` is exceeded by every request. Since it needs no\n * storage, it is not backed by the {@link RateLimitsOptions.factory}, and\n * applies even when no rate limits are configured.\n */\nexport type RateLimitRule<C extends RateLimitContext = RateLimitContext> = {\n key: RateLimitKeyGetter<C>\n points: number\n durationMs: number\n}\n\nexport interface RateLimitPolicy<\n C extends RateLimitContext = RateLimitContext,\n> {\n /**\n * Exceeding any of these rules rejects the request with a\n * `rate_limit_exceeded` (HTTP 429) error.\n *\n * @note Never key a rule on the identifier alone here (e.g. using\n * {@link identifierKey}), as that would allow anyone to lock a victim out of\n * their account.\n */\n block: readonly RateLimitRule<C>[]\n}\n\nexport interface RateLimitDevicePolicy<\n C extends RateLimitDeviceContext = RateLimitDeviceContext,\n> extends RateLimitPolicy<C> {\n /**\n * Exceeding any of these rules requires the request to carry a valid hCaptcha\n * token. Ignored when hCaptcha is not configured.\n */\n captcha: readonly RateLimitRule<C>[]\n}\n\nexport type RateLimitPolicies = {\n readonly [P in RateLimitPolicyName]: P extends RateLimitDevicePolicyName\n ? RateLimitDevicePolicy<RateLimitPolicyContexts[P]>\n : RateLimitPolicy<RateLimitPolicyContexts[P]>\n}\n\nexport const DEFAULT_RATE_LIMIT_POLICIES: RateLimitPolicies = {\n 'sign-in': {\n captcha: [\n { key: identifierKey, points: 5, durationMs: 15 * MINUTE },\n { key: ipKey, points: 20, durationMs: 15 * MINUTE },\n ],\n block: [\n { key: identifierIpKey, points: 25, durationMs: 5 * MINUTE },\n { key: identifierIpKey, points: 50, durationMs: DAY },\n { key: ipKey, points: 100, durationMs: 5 * MINUTE },\n ],\n },\n 'sign-up': {\n // @NOTE No points: every sign-up requires a captcha\n captcha: [{ key: ipKey, points: 0, durationMs: 0 }],\n block: [\n { key: ipKey, points: 20, durationMs: HOUR },\n { key: ipKey, points: 100, durationMs: DAY },\n ],\n },\n 'reset-password-request': {\n captcha: [\n { key: identifierKey, points: 3, durationMs: HOUR },\n { key: ipKey, points: 5, durationMs: HOUR },\n ],\n block: [\n { key: ipKey, points: 15, durationMs: HOUR },\n { key: ipKey, points: 50, durationMs: DAY },\n ],\n },\n 'reset-password-confirm': {\n captcha: [{ key: ipKey, points: 5, durationMs: 15 * MINUTE }],\n block: [{ key: ipKey, points: 50, durationMs: 5 * MINUTE }],\n },\n 'pushed-authorization-request': {\n block: [\n // @NOTE Shared by all the users of the client, hence the higher limit\n { key: authenticatedClientKey, points: 3000, durationMs: 5 * MINUTE },\n // @NOTE Unauthenticated clients are typically not running on a server\n // and are initiating requests from devices with dynamic IPs.\n { key: publicClientIpKey, points: 50, durationMs: 5 * MINUTE },\n ],\n },\n}\n\nexport type RateLimitsOptions = {\n factory: RateLimiterFactory\n\n /**\n * Overrides {@link DEFAULT_RATE_LIMIT_POLICIES}. Each tier provided replaces\n * the corresponding default tier's rules entirely.\n */\n policies?: {\n readonly [P in RateLimitPolicyName]?: Partial<RateLimitPolicies[P]>\n }\n}\n"]}
@@ -0,0 +1,36 @@
1
+ export type RateLimiterOptions = {
2
+ /**
3
+ * Stable and unique identifier of the limiter. Implementations typically use
4
+ * it to namespace their storage keys, so it must not change across deploys.
5
+ */
6
+ name: string;
7
+ points: number;
8
+ durationMs: number;
9
+ };
10
+ export type RateLimiterConsumeResult = {
11
+ /**
12
+ * `points` minus the points consumed in the current window, including the
13
+ * ones just consumed. Must **not** be clamped to `0`: a negative value means
14
+ * that the limit was exceeded.
15
+ */
16
+ remainingPoints: number;
17
+ msBeforeNext: number;
18
+ };
19
+ /**
20
+ * Backend implementation of a fixed window rate limiter, provided by the host
21
+ * through a {@link RateLimiterFactory}.
22
+ *
23
+ * Backend failures (e.g. storage unavailable) are the implementation's concern:
24
+ * it may either throw, causing the request being processed to fail (fail
25
+ * closed), or swallow the error and report the key as not limited (fail open).
26
+ */
27
+ export interface RateLimiter {
28
+ /**
29
+ * Consumes `points` for `key`. This method must **not**
30
+ * throw when the limit is exceeded; it must return a negative
31
+ * `remainingPoints` instead.
32
+ */
33
+ consume(key: string, points: number): Promise<RateLimiterConsumeResult>;
34
+ }
35
+ export type RateLimiterFactory = (options: RateLimiterOptions) => RateLimiter;
36
+ //# sourceMappingURL=rate-limiter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limiter.d.ts","sourceRoot":"","sources":["../../src/rate-limit/rate-limiter.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAA;IACZ,MAAM,EAAE,MAAM,CAAA;IACd,UAAU,EAAE,MAAM,CAAA;CACnB,CAAA;AAED,MAAM,MAAM,wBAAwB,GAAG;IACrC;;;;OAIG;IACH,eAAe,EAAE,MAAM,CAAA;IACvB,YAAY,EAAE,MAAM,CAAA;CACrB,CAAA;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,WAAW;IAC1B;;;;OAIG;IACH,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAAA;CACxE;AAED,MAAM,MAAM,kBAAkB,GAAG,CAAC,OAAO,EAAE,kBAAkB,KAAK,WAAW,CAAA"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=rate-limiter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limiter.js","sourceRoot":"","sources":["../../src/rate-limit/rate-limiter.ts"],"names":[],"mappings":"","sourcesContent":["export type RateLimiterOptions = {\n /**\n * Stable and unique identifier of the limiter. Implementations typically use\n * it to namespace their storage keys, so it must not change across deploys.\n */\n name: string\n points: number\n durationMs: number\n}\n\nexport type RateLimiterConsumeResult = {\n /**\n * `points` minus the points consumed in the current window, including the\n * ones just consumed. Must **not** be clamped to `0`: a negative value means\n * that the limit was exceeded.\n */\n remainingPoints: number\n msBeforeNext: number\n}\n\n/**\n * Backend implementation of a fixed window rate limiter, provided by the host\n * through a {@link RateLimiterFactory}.\n *\n * Backend failures (e.g. storage unavailable) are the implementation's concern:\n * it may either throw, causing the request being processed to fail (fail\n * closed), or swallow the error and report the key as not limited (fail open).\n */\nexport interface RateLimiter {\n /**\n * Consumes `points` for `key`. This method must **not**\n * throw when the limit is exceeded; it must return a negative\n * `remainingPoints` instead.\n */\n consume(key: string, points: number): Promise<RateLimiterConsumeResult>\n}\n\nexport type RateLimiterFactory = (options: RateLimiterOptions) => RateLimiter\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"send-error-page.d.ts","sourceRoot":"","sources":["../../../src/router/assets/send-error-page.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAChE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sCAAsC,CAAA;AAKzE,OAAO,EAAE,KAAK,iBAAiB,EAAqB,MAAM,aAAa,CAAA;AAEvE,wBAAgB,oBAAoB,CAClC,aAAa,EAAE,aAAa,EAC5B,OAAO,CAAC,EAAE,iBAAiB,SAKpB,eAAe,OACf,cAAc,OACd,OAAO,KACX,OAAO,CAAC,IAAI,CAAC,CAMjB"}
1
+ {"version":3,"file":"send-error-page.d.ts","sourceRoot":"","sources":["../../../src/router/assets/send-error-page.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAChE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sCAAsC,CAAA;AAKzE,OAAO,EAAE,KAAK,iBAAiB,EAAqB,MAAM,aAAa,CAAA;AAEvE,wBAAgB,oBAAoB,CAClC,aAAa,EAAE,aAAa,EAC5B,OAAO,CAAC,EAAE,iBAAiB,SAKpB,eAAe,OACf,cAAc,OACd,OAAO,KACX,OAAO,CAAC,IAAI,CAAC,CAOjB"}
@@ -3,9 +3,10 @@ import { sendWebAppFactory } from './assets.js';
3
3
  export function sendErrorPageFactory(customization, options) {
4
4
  const sendApp = sendWebAppFactory('error-page', customization, options);
5
5
  return async function sendErrorPage(req, res, err) {
6
+ const status = buildErrorStatus(err);
6
7
  return sendApp(req, res, {
7
- status: buildErrorStatus(err),
8
- data: { __errorData: buildErrorPayload(err) },
8
+ status,
9
+ data: { __errorStatus: status, __errorData: buildErrorPayload(err) },
9
10
  });
10
11
  };
11
12
  }
@@ -1 +1 @@
1
- {"version":3,"file":"send-error-page.js","sourceRoot":"","sources":["../../../src/router/assets/send-error-page.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,8BAA8B,CAAA;AACrC,OAAO,EAA0B,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAEvE,MAAM,UAAU,oBAAoB,CAClC,aAA4B,EAC5B,OAA2B;IAE3B,MAAM,OAAO,GAAG,iBAAiB,CAAC,YAAY,EAAE,aAAa,EAAE,OAAO,CAAC,CAAA;IAEvE,OAAO,KAAK,UAAU,aAAa,CACjC,GAAoB,EACpB,GAAmB,EACnB,GAAY;QAEZ,OAAO,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE;YACvB,MAAM,EAAE,gBAAgB,CAAC,GAAG,CAAC;YAC7B,IAAI,EAAE,EAAE,WAAW,EAAE,iBAAiB,CAAC,GAAG,CAAC,EAAE;SAC9C,CAAC,CAAA;IACJ,CAAC,CAAA;AACH,CAAC","sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Customization } from '../../customization/customization.js'\nimport {\n buildErrorPayload,\n buildErrorStatus,\n} from '../../errors/error-parser.js'\nimport { type SendWebAppOptions, sendWebAppFactory } from './assets.js'\n\nexport function sendErrorPageFactory(\n customization: Customization,\n options?: SendWebAppOptions,\n) {\n const sendApp = sendWebAppFactory('error-page', customization, options)\n\n return async function sendErrorPage(\n req: IncomingMessage,\n res: ServerResponse,\n err: unknown,\n ): Promise<void> {\n return sendApp(req, res, {\n status: buildErrorStatus(err),\n data: { __errorData: buildErrorPayload(err) },\n })\n }\n}\n"]}
1
+ {"version":3,"file":"send-error-page.js","sourceRoot":"","sources":["../../../src/router/assets/send-error-page.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,8BAA8B,CAAA;AACrC,OAAO,EAA0B,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAEvE,MAAM,UAAU,oBAAoB,CAClC,aAA4B,EAC5B,OAA2B;IAE3B,MAAM,OAAO,GAAG,iBAAiB,CAAC,YAAY,EAAE,aAAa,EAAE,OAAO,CAAC,CAAA;IAEvE,OAAO,KAAK,UAAU,aAAa,CACjC,GAAoB,EACpB,GAAmB,EACnB,GAAY;QAEZ,MAAM,MAAM,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAAA;QACpC,OAAO,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE;YACvB,MAAM;YACN,IAAI,EAAE,EAAE,aAAa,EAAE,MAAM,EAAE,WAAW,EAAE,iBAAiB,CAAC,GAAG,CAAC,EAAE;SACrE,CAAC,CAAA;IACJ,CAAC,CAAA;AACH,CAAC","sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { Customization } from '../../customization/customization.js'\nimport {\n buildErrorPayload,\n buildErrorStatus,\n} from '../../errors/error-parser.js'\nimport { type SendWebAppOptions, sendWebAppFactory } from './assets.js'\n\nexport function sendErrorPageFactory(\n customization: Customization,\n options?: SendWebAppOptions,\n) {\n const sendApp = sendWebAppFactory('error-page', customization, options)\n\n return async function sendErrorPage(\n req: IncomingMessage,\n res: ServerResponse,\n err: unknown,\n ): Promise<void> {\n const status = buildErrorStatus(err)\n return sendApp(req, res, {\n status,\n data: { __errorStatus: status, __errorData: buildErrorPayload(err) },\n })\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"create-api-middleware.d.ts","sourceRoot":"","sources":["../../src/router/create-api-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAgChE,OAAO,EAEL,KAAK,UAAU,EAahB,MAAM,sBAAsB,CAAA;AAI7B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAWzD,OAAO,EAEL,KAAK,oBAAoB,EAM1B,MAAM,2BAA2B,CAAA;AAClC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAA;AAEhE,wBAAgB,mBAAmB,CACjC,GAAG,SAAS,MAAM,GAAG,IAAI,GAAG,IAAI,EAChC,GAAG,SAAS,eAAe,GAAG,eAAe,EAC7C,GAAG,SAAS,cAAc,GAAG,cAAc,EAE3C,MAAM,EAAE,aAAa,EACrB,EAAE,OAAO,EAAE,EAAE,iBAAiB,CAAC,GAAG,EAAE,GAAG,CAAC,GACvC,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAg9B3B;AA2BD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,GAAG,GAAG,oBAAoB,CA4C/D"}
1
+ {"version":3,"file":"create-api-middleware.d.ts","sourceRoot":"","sources":["../../src/router/create-api-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AA+BhE,OAAO,EAEL,KAAK,UAAU,EAahB,MAAM,sBAAsB,CAAA;AAK7B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAA;AAYzD,OAAO,EAEL,KAAK,oBAAoB,EAM1B,MAAM,2BAA2B,CAAA;AAClC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAA;AAMhE,wBAAgB,mBAAmB,CACjC,GAAG,SAAS,MAAM,GAAG,IAAI,GAAG,IAAI,EAChC,GAAG,SAAS,eAAe,GAAG,eAAe,EAC7C,GAAG,SAAS,cAAc,GAAG,cAAc,EAE3C,MAAM,EAAE,aAAa,EACrB,EAAE,OAAO,EAAE,EAAE,iBAAiB,CAAC,GAAG,EAAE,GAAG,CAAC,GACvC,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAogC3B;AAkCD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,GAAG,GAAG,oBAAoB,CA4C/D"}
@@ -4,25 +4,29 @@ import { didSchema } from '@atproto/did';
4
4
  import { signedJwtSchema } from '@atproto/jwk';
5
5
  import { API_ENDPOINT_PREFIX } from '@atproto/oauth-provider-api';
6
6
  import { oauthRedirectUriSchema, oauthResponseModeSchema, oauthScopeSchema, } from '@atproto/oauth-types';
7
- import { signInDataSchema } from '../account/sign-in-data.js';
8
- import { signUpInputSchema } from '../account/sign-up-input.js';
9
7
  import { deviceIdSchema } from '../device/device-id.js';
10
8
  import { AuthorizationError } from '../errors/authorization-error.js';
11
9
  import { buildErrorPayload, buildErrorStatus, } from '../errors/error-parser.js';
12
10
  import { InvalidRequestError } from '../errors/invalid-request-error.js';
13
11
  import { WWWAuthenticateError } from '../errors/www-authenticate-error.js';
12
+ import { hcaptchaTokenSchema } from '../lib/hcaptcha.js';
14
13
  import { Router, flushStream, jsonHandler, parseHttpRequest, subCtx, validateFetchMode, validateFetchSite, validateOrigin, validateReferrer, } from '../lib/http/index.js';
15
14
  import { createRoute } from '../lib/http/route.js';
16
15
  import { localeSchema } from '../lib/util/locale.js';
16
+ import { OAuthError } from '../oauth-errors.js';
17
17
  import { requestUriSchema } from '../request/request-uri.js';
18
18
  import { tokenIdSchema } from '../token/token-id.js';
19
19
  import { emailOtpSchema } from '../types/email-otp.js';
20
20
  import { emailSchema, newEmailSchema } from '../types/email.js';
21
21
  import { handleSchema } from '../types/handle.js';
22
22
  import { identifierSchema } from '../types/indentifier.js';
23
+ import { inviteCodeSchema } from '../types/invite-code.js';
23
24
  import { newPasswordSchema, oldPasswordSchema } from '../types/password.js';
24
25
  import { validateCsrfToken } from './assets/csrf.js';
25
26
  import { ERROR_REDIRECT_KEYS, SUCCESS_REDIRECT_KEYS, buildRedirectMode, buildRedirectParams, buildRedirectUri, } from './assets/send-redirect.js';
27
+ // @TODO Add rate limits to the remaining routes: /oauth/token, /oauth/revoke,
28
+ // and the account API routes not covered by RateLimitManager policies (e.g.
29
+ // verify-handle-availability, authenticated account management).
26
30
  export function createApiMiddleware(server, { onError }) {
27
31
  const issuerUrl = new URL(server.issuer);
28
32
  const issuerOrigin = issuerUrl.origin;
@@ -39,10 +43,26 @@ export function createApiMiddleware(server, { onError }) {
39
43
  router.use(apiRoute({
40
44
  method: 'POST',
41
45
  endpoint: '/sign-up',
42
- schema: signUpInputSchema,
46
+ schema: z
47
+ .object({
48
+ locale: localeSchema,
49
+ handle: handleSchema,
50
+ email: newEmailSchema,
51
+ password: newPasswordSchema,
52
+ remember: z.boolean().optional(),
53
+ inviteCode: inviteCodeSchema.optional(),
54
+ hcaptchaToken: hcaptchaTokenSchema.optional(),
55
+ })
56
+ .strict(),
43
57
  rotateDeviceCookies: true,
44
58
  async handler() {
45
59
  const { deviceId, deviceMetadata, input, requestUri } = this;
60
+ await server.rateLimitManager.consume('sign-up', {
61
+ kind: 'device',
62
+ deviceId,
63
+ deviceMetadata,
64
+ data: { action: 'sign-up', input },
65
+ });
46
66
  const clientId = requestUri
47
67
  ? await server.requestManager.peekClientId(requestUri)
48
68
  : undefined;
@@ -61,16 +81,31 @@ export function createApiMiddleware(server, { onError }) {
61
81
  router.use(apiRoute({
62
82
  method: 'POST',
63
83
  endpoint: '/sign-in',
64
- schema: signInDataSchema,
84
+ schema: z
85
+ .object({
86
+ locale: localeSchema,
87
+ identifier: identifierSchema,
88
+ password: z.union([oldPasswordSchema, newPasswordSchema]),
89
+ emailOtp: emailOtpSchema.optional(),
90
+ remember: z.boolean().optional(),
91
+ hcaptchaToken: hcaptchaTokenSchema.optional(),
92
+ })
93
+ .strict(),
65
94
  rotateDeviceCookies: true,
66
95
  async handler() {
67
- const { deviceId, deviceMetadata, requestUri } = this;
96
+ const { deviceId, deviceMetadata, requestUri, input } = this;
97
+ await server.rateLimitManager.consume('sign-in', {
98
+ kind: 'device',
99
+ deviceId,
100
+ deviceMetadata,
101
+ data: { action: 'sign-in', input },
102
+ });
68
103
  // Look up the client identifier associated with the pending OAuth
69
104
  // request, if any, so it can be surfaced to the sign-in hooks.
70
105
  const clientId = requestUri
71
106
  ? await server.requestManager.peekClientId(requestUri)
72
107
  : undefined;
73
- const { account, remembered } = await server.accountManager.authenticateAccount(deviceId, deviceMetadata, this.input, clientId);
108
+ const { account, remembered } = await server.accountManager.authenticateAccount(deviceId, deviceMetadata, input, clientId);
74
109
  // If the user was not "remembered", it's device-account association was
75
110
  // removed and any future interaction will require an ephemeral token
76
111
  // to authenticate the user.
@@ -101,10 +136,18 @@ export function createApiMiddleware(server, { onError }) {
101
136
  .object({
102
137
  identifier: identifierSchema,
103
138
  locale: localeSchema,
139
+ hcaptchaToken: hcaptchaTokenSchema.optional(),
104
140
  })
105
141
  .strict(),
106
142
  async handler() {
107
- await server.accountManager.resetPasswordRequest(this.deviceId, this.deviceMetadata, this.input);
143
+ const { deviceId, deviceMetadata, input } = this;
144
+ await server.rateLimitManager.consume('reset-password-request', {
145
+ kind: 'device',
146
+ deviceId,
147
+ deviceMetadata,
148
+ data: { action: 'reset-password-request', input },
149
+ });
150
+ await server.accountManager.resetPasswordRequest(deviceId, deviceMetadata, input);
108
151
  return { json: { success: true } };
109
152
  },
110
153
  }));
@@ -115,10 +158,18 @@ export function createApiMiddleware(server, { onError }) {
115
158
  .object({
116
159
  token: emailOtpSchema,
117
160
  password: newPasswordSchema,
161
+ hcaptchaToken: hcaptchaTokenSchema.optional(),
118
162
  })
119
163
  .strict(),
120
164
  async handler() {
121
- await server.accountManager.resetPasswordConfirm(this.deviceId, this.deviceMetadata, this.input);
165
+ const { deviceId, deviceMetadata, input } = this;
166
+ await server.rateLimitManager.consume('reset-password-confirm', {
167
+ kind: 'device',
168
+ deviceId,
169
+ deviceMetadata,
170
+ data: { action: 'reset-password-confirm', input },
171
+ });
172
+ await server.accountManager.resetPasswordConfirm(deviceId, deviceMetadata, input);
122
173
  return { json: { success: true } };
123
174
  },
124
175
  }));
@@ -467,7 +518,7 @@ export function createApiMiddleware(server, { onError }) {
467
518
  // @NOTE Not re-throwing the error here, as the error was already
468
519
  // handled by the `onError` callback, and apiRoute (`apiMiddleware`)
469
520
  // would call `onError` again.
470
- return buildErrorJsonResponse(err);
521
+ return buildErrorJsonResponse(res, err);
471
522
  }
472
523
  },
473
524
  }));
@@ -510,7 +561,7 @@ export function createApiMiddleware(server, { onError }) {
510
561
  // Unable to build redirect URL, ignore
511
562
  }
512
563
  }
513
- return buildErrorJsonResponse(err);
564
+ return buildErrorJsonResponse(res, err);
514
565
  }
515
566
  finally {
516
567
  await server.requestManager.delete(requestUri).catch((err) => {
@@ -538,9 +589,9 @@ export function createApiMiddleware(server, { onError }) {
538
589
  }
539
590
  }
540
591
  catch (err) {
541
- throw err instanceof WWWAuthenticateError
542
- ? err
543
- : new WWWAuthenticateError('unauthorized', `Invalid or expired bearer token`, { Bearer: {} }, err);
592
+ if (err instanceof WWWAuthenticateError)
593
+ throw err;
594
+ throw new WWWAuthenticateError('unauthorized', `Invalid or expired bearer token`, { Bearer: {} }, err);
544
595
  }
545
596
  }
546
597
  try {
@@ -619,12 +670,18 @@ export function createApiMiddleware(server, { onError }) {
619
670
  catch (err) {
620
671
  onError?.(req, res, err, `Failed to handle API request`);
621
672
  // Make sore to always return a JSON response
622
- return buildErrorJsonResponse(err);
673
+ return buildErrorJsonResponse(res, err);
623
674
  }
624
675
  });
625
676
  }
626
677
  }
627
- function buildErrorJsonResponse(err) {
678
+ function buildErrorJsonResponse(res, err) {
679
+ if (!res.headersSent && err instanceof OAuthError) {
680
+ for (const [name, value] of err.getResponseHeaders()) {
681
+ res.setHeader(name, value);
682
+ res.appendHeader('Access-Control-Expose-Headers', name);
683
+ }
684
+ }
628
685
  // @TODO Rework the API error responses (relying on codes)
629
686
  const json = buildErrorPayload(err);
630
687
  const status = buildErrorStatus(err);