authfn 0.1.2 → 0.3.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 (126) hide show
  1. package/README.md +47 -292
  2. package/dist/core/account-linking.d.ts +30 -0
  3. package/dist/core/account-linking.d.ts.map +1 -0
  4. package/dist/core/account-linking.js +80 -0
  5. package/dist/core/account-linking.js.map +1 -0
  6. package/dist/core/account.d.ts +38 -0
  7. package/dist/core/account.d.ts.map +1 -0
  8. package/dist/core/account.js +164 -0
  9. package/dist/core/account.js.map +1 -0
  10. package/dist/core/admin-users.d.ts +50 -0
  11. package/dist/core/admin-users.d.ts.map +1 -0
  12. package/dist/core/admin-users.js +227 -0
  13. package/dist/core/admin-users.js.map +1 -0
  14. package/dist/core/api-keys.d.ts +40 -0
  15. package/dist/core/api-keys.d.ts.map +1 -0
  16. package/dist/core/api-keys.js +175 -0
  17. package/dist/core/api-keys.js.map +1 -0
  18. package/dist/core/cache.d.ts +18 -0
  19. package/dist/core/cache.d.ts.map +1 -0
  20. package/dist/core/cache.js +54 -0
  21. package/dist/core/cache.js.map +1 -0
  22. package/dist/core/cookies.d.ts +25 -0
  23. package/dist/core/cookies.d.ts.map +1 -0
  24. package/dist/core/cookies.js +89 -0
  25. package/dist/core/cookies.js.map +1 -0
  26. package/dist/core/delivery.d.ts +4 -0
  27. package/dist/core/delivery.d.ts.map +1 -0
  28. package/dist/core/delivery.js +37 -0
  29. package/dist/core/delivery.js.map +1 -0
  30. package/dist/core/environment.d.ts +4 -0
  31. package/dist/core/environment.d.ts.map +1 -0
  32. package/dist/core/environment.js +50 -0
  33. package/dist/core/environment.js.map +1 -0
  34. package/dist/core/errors.d.ts +123 -0
  35. package/dist/core/errors.d.ts.map +1 -0
  36. package/dist/core/errors.js +437 -0
  37. package/dist/core/errors.js.map +1 -0
  38. package/dist/core/gateway-routing.d.ts +88 -0
  39. package/dist/core/gateway-routing.d.ts.map +1 -0
  40. package/dist/core/gateway-routing.js +902 -0
  41. package/dist/core/gateway-routing.js.map +1 -0
  42. package/dist/core/limits.d.ts +4 -0
  43. package/dist/core/limits.d.ts.map +1 -0
  44. package/dist/core/limits.js +13 -0
  45. package/dist/core/limits.js.map +1 -0
  46. package/dist/core/oauth-accounts.d.ts +29 -0
  47. package/dist/core/oauth-accounts.d.ts.map +1 -0
  48. package/dist/core/oauth-accounts.js +123 -0
  49. package/dist/core/oauth-accounts.js.map +1 -0
  50. package/dist/core/observability.d.ts +4 -0
  51. package/dist/core/observability.d.ts.map +1 -0
  52. package/dist/core/observability.js +38 -0
  53. package/dist/core/observability.js.map +1 -0
  54. package/dist/core/passwords.d.ts +52 -0
  55. package/dist/core/passwords.d.ts.map +1 -0
  56. package/dist/core/passwords.js +468 -0
  57. package/dist/core/passwords.js.map +1 -0
  58. package/dist/core/placement-context.d.ts +90 -0
  59. package/dist/core/placement-context.d.ts.map +1 -0
  60. package/dist/core/placement-context.js +620 -0
  61. package/dist/core/placement-context.js.map +1 -0
  62. package/dist/core/plugin-runtime.d.ts +8 -0
  63. package/dist/core/plugin-runtime.d.ts.map +1 -0
  64. package/dist/core/plugin-runtime.js +15 -0
  65. package/dist/core/plugin-runtime.js.map +1 -0
  66. package/dist/core/rate-limit.d.ts +4 -0
  67. package/dist/core/rate-limit.d.ts.map +1 -0
  68. package/dist/core/rate-limit.js +177 -0
  69. package/dist/core/rate-limit.js.map +1 -0
  70. package/dist/core/regions.d.ts +47 -0
  71. package/dist/core/regions.d.ts.map +1 -0
  72. package/dist/core/regions.js +642 -0
  73. package/dist/core/regions.js.map +1 -0
  74. package/dist/core/session-responses.d.ts +10 -0
  75. package/dist/core/session-responses.d.ts.map +1 -0
  76. package/dist/core/session-responses.js +22 -0
  77. package/dist/core/session-responses.js.map +1 -0
  78. package/dist/core/sessions.d.ts +53 -0
  79. package/dist/core/sessions.d.ts.map +1 -0
  80. package/dist/core/sessions.js +442 -0
  81. package/dist/core/sessions.js.map +1 -0
  82. package/dist/core/two-factor.d.ts +34 -0
  83. package/dist/core/two-factor.d.ts.map +1 -0
  84. package/dist/core/two-factor.js +511 -0
  85. package/dist/core/two-factor.js.map +1 -0
  86. package/dist/core/users.d.ts +12 -0
  87. package/dist/core/users.d.ts.map +1 -0
  88. package/dist/core/users.js +74 -0
  89. package/dist/core/users.js.map +1 -0
  90. package/dist/core/verifications.d.ts +52 -0
  91. package/dist/core/verifications.d.ts.map +1 -0
  92. package/dist/core/verifications.js +522 -0
  93. package/dist/core/verifications.js.map +1 -0
  94. package/dist/http/envelopes.d.ts +10 -0
  95. package/dist/http/envelopes.d.ts.map +1 -0
  96. package/dist/http/envelopes.js +99 -0
  97. package/dist/http/envelopes.js.map +1 -0
  98. package/dist/http/router.d.ts +16 -0
  99. package/dist/http/router.d.ts.map +1 -0
  100. package/dist/http/router.js +347 -0
  101. package/dist/http/router.js.map +1 -0
  102. package/dist/index.d.ts +18 -0
  103. package/dist/index.d.ts.map +1 -0
  104. package/dist/index.js +108 -0
  105. package/dist/index.js.map +1 -0
  106. package/dist/openapi.d.ts +4 -0
  107. package/dist/openapi.d.ts.map +1 -0
  108. package/dist/openapi.js +43 -0
  109. package/dist/openapi.js.map +1 -0
  110. package/dist/plugin-runner.d.ts +12 -0
  111. package/dist/plugin-runner.d.ts.map +1 -0
  112. package/dist/plugin-runner.js +206 -0
  113. package/dist/plugin-runner.js.map +1 -0
  114. package/dist/plugin-types.d.ts +205 -0
  115. package/dist/plugin-types.d.ts.map +1 -0
  116. package/dist/plugin-types.js +2 -0
  117. package/dist/plugin-types.js.map +1 -0
  118. package/dist/schema.d.ts +7 -0
  119. package/dist/schema.d.ts.map +1 -0
  120. package/dist/schema.js +127 -0
  121. package/dist/schema.js.map +1 -0
  122. package/dist/types.d.ts +444 -0
  123. package/dist/types.d.ts.map +1 -0
  124. package/dist/types.js +2 -0
  125. package/dist/types.js.map +1 -0
  126. package/package.json +85 -59
@@ -0,0 +1,43 @@
1
+ import { joinPaths } from '@superfunctions/http';
2
+ import { OpenApiGenerationError, generateOpenApiDocument } from '@superfunctions/http-openapi';
3
+ import { AuthFnInternalError } from './core/errors.js';
4
+ export function createAuthFnOpenApiDocument(config, router) {
5
+ const metadata = resolveOpenApiMetadata(config);
6
+ try {
7
+ return generateOpenApiDocument({
8
+ title: metadata.title,
9
+ version: metadata.version,
10
+ routers: [withBasePath(router, config.basePath ?? '/auth')]
11
+ });
12
+ }
13
+ catch (error) {
14
+ if (error instanceof OpenApiGenerationError) {
15
+ throw new AuthFnInternalError('Failed to generate authfn OpenAPI document', {
16
+ code: error.code,
17
+ method: error.details?.method,
18
+ path: error.details?.path
19
+ });
20
+ }
21
+ throw error;
22
+ }
23
+ }
24
+ function resolveOpenApiMetadata(config) {
25
+ if (typeof config.openApi === 'object') {
26
+ return config.openApi;
27
+ }
28
+ return {
29
+ title: 'AuthFn API',
30
+ version: '0.0.1'
31
+ };
32
+ }
33
+ function withBasePath(router, basePath) {
34
+ return {
35
+ getRoutes() {
36
+ return router.getRoutes().map((route) => ({
37
+ ...route,
38
+ path: joinPaths(basePath, route.path)
39
+ }));
40
+ }
41
+ };
42
+ }
43
+ //# sourceMappingURL=openapi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openapi.js","sourceRoot":"","sources":["../src/openapi.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAA2B,MAAM,sBAAsB,CAAC;AAC1E,OAAO,EACL,sBAAsB,EACtB,uBAAuB,EACxB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAGvD,MAAM,UAAU,2BAA2B,CACzC,MAAyD,EACzD,MAAiC;IAEjC,MAAM,QAAQ,GAAG,sBAAsB,CAAC,MAAM,CAAC,CAAC;IAEhD,IAAI,CAAC;QACH,OAAO,uBAAuB,CAAC;YAC7B,KAAK,EAAE,QAAQ,CAAC,KAAK;YACrB,OAAO,EAAE,QAAQ,CAAC,OAAO;YACzB,OAAO,EAAE,CAAC,YAAY,CAAC,MAAM,EAAE,MAAM,CAAC,QAAQ,IAAI,OAAO,CAAC,CAAC;SAC5D,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,sBAAsB,EAAE,CAAC;YAC5C,MAAM,IAAI,mBAAmB,CAAC,4CAA4C,EAAE;gBAC1E,IAAI,EAAE,KAAK,CAAC,IAAI;gBAChB,MAAM,EAAE,KAAK,CAAC,OAAO,EAAE,MAAM;gBAC7B,IAAI,EAAE,KAAK,CAAC,OAAO,EAAE,IAAI;aAC1B,CAAC,CAAC;QACL,CAAC;QAED,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,SAAS,sBAAsB,CAC7B,MAA4C;IAE5C,IAAI,OAAO,MAAM,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;QACvC,OAAO,MAAM,CAAC,OAAO,CAAC;IACxB,CAAC;IAED,OAAO;QACL,KAAK,EAAE,YAAY;QACnB,OAAO,EAAE,OAAO;KACjB,CAAC;AACJ,CAAC;AAED,SAAS,YAAY,CACnB,MAAiC,EACjC,QAAgB;IAEhB,OAAO;QACL,SAAS;YACP,OAAO,MAAM,CAAC,SAAS,EAAE,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;gBACxC,GAAG,KAAK;gBACR,IAAI,EAAE,SAAS,CAAC,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC;aACtC,CAAC,CAAC,CAAC;QACN,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,12 @@
1
+ import type { Route } from '@superfunctions/http';
2
+ import type { AuthFnRuntimeConfig, AuthFnHooks, AuthFnPluginRuntimeContext } from './types.js';
3
+ export interface AuthFnPluginRunner {
4
+ routes: Route[];
5
+ hooks: Partial<AuthFnHooks>;
6
+ }
7
+ export declare function createPluginRuntimeContext(config: AuthFnRuntimeConfig, hooks?: Partial<AuthFnHooks>): AuthFnPluginRuntimeContext;
8
+ export declare function validatePlugins(config: AuthFnRuntimeConfig): void;
9
+ export declare function composePluginRoutes(config: AuthFnRuntimeConfig, hooks?: Partial<AuthFnHooks>): Route[];
10
+ export declare function composePluginHooks(config: AuthFnRuntimeConfig): Partial<AuthFnHooks>;
11
+ export declare function createPluginRunner(config: AuthFnRuntimeConfig): AuthFnPluginRunner;
12
+ //# sourceMappingURL=plugin-runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin-runner.d.ts","sourceRoot":"","sources":["../src/plugin-runner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,KAAK,EACV,mBAAmB,EAMnB,WAAW,EAEX,0BAA0B,EAE3B,MAAM,YAAY,CAAC;AAwBpB,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,KAAK,EAAE,CAAC;IAChB,KAAK,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;CAC7B;AAED,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,mBAAmB,EAC3B,KAAK,GAAE,OAAO,CAAC,WAAW,CAAsB,GAC/C,0BAA0B,CAQ5B;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,mBAAmB,GAAG,IAAI,CAIjE;AAED,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,mBAAmB,EAC3B,KAAK,GAAE,OAAO,CAAC,WAAW,CAA8B,GACvD,KAAK,EAAE,CAGT;AAED,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,mBAAmB,GAAG,OAAO,CAAC,WAAW,CAAC,CAyBpF;AAED,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,mBAAmB,GAAG,kBAAkB,CAOlF"}
@@ -0,0 +1,206 @@
1
+ import { AuthFnError as AuthFnErrorClass, AuthFnPluginAbortedError } from './core/errors.js';
2
+ import { emitAuthEvent, eventRequestId } from './core/observability.js';
3
+ const BEFORE_HOOK_NAMES = [
4
+ 'beforeUserCreate',
5
+ 'beforeSessionIssue',
6
+ 'beforeChallengeSend',
7
+ 'beforeOAuthStart',
8
+ 'beforeAccountDelete'
9
+ ];
10
+ const AFTER_HOOK_NAMES = [
11
+ 'afterUserCreate',
12
+ 'afterSessionIssue',
13
+ 'afterChallengeSend',
14
+ 'afterOAuthCallback',
15
+ 'afterAccountDelete',
16
+ 'afterAccountDeleteFailure'
17
+ ];
18
+ export function createPluginRuntimeContext(config, hooks = config.hooks ?? {}) {
19
+ return {
20
+ config,
21
+ namespace: config.namespace ?? 'authfn',
22
+ basePath: config.basePath ?? '/auth',
23
+ hooks,
24
+ environment: config.environment
25
+ };
26
+ }
27
+ export function validatePlugins(config) {
28
+ for (const plugin of config.plugins) {
29
+ plugin.validateConfig?.(config);
30
+ }
31
+ }
32
+ export function composePluginRoutes(config, hooks = composePluginHooks(config)) {
33
+ const runtimeContext = createPluginRuntimeContext(config, hooks);
34
+ return config.plugins.flatMap((plugin) => plugin.routes?.(runtimeContext) ?? []);
35
+ }
36
+ export function composePluginHooks(config) {
37
+ return {
38
+ beforeUserCreate: async (ctx, input) => runBeforeHooks(config.plugins, config, config.hooks, 'beforeUserCreate', ctx, input),
39
+ beforeSessionIssue: async (ctx, input) => runBeforeHooks(config.plugins, config, config.hooks, 'beforeSessionIssue', ctx, input),
40
+ beforeChallengeSend: async (ctx, input) => runBeforeHooks(config.plugins, config, config.hooks, 'beforeChallengeSend', ctx, input),
41
+ beforeOAuthStart: async (ctx, input) => runBeforeHooks(config.plugins, config, config.hooks, 'beforeOAuthStart', ctx, input),
42
+ beforeAccountDelete: async (ctx, input) => runBeforeHooks(config.plugins, config, config.hooks, 'beforeAccountDelete', ctx, input),
43
+ afterUserCreate: async (ctx, user) => runAfterHooks(config.plugins, config, config.hooks, 'afterUserCreate', ctx, user),
44
+ afterSessionIssue: async (ctx, session) => runAfterHooks(config.plugins, config, config.hooks, 'afterSessionIssue', ctx, session),
45
+ afterChallengeSend: async (ctx, result) => runAfterHooks(config.plugins, config, config.hooks, 'afterChallengeSend', ctx, result),
46
+ afterOAuthCallback: async (ctx, result) => runAfterHooks(config.plugins, config, config.hooks, 'afterOAuthCallback', ctx, result),
47
+ afterAccountDelete: async (ctx, result) => runAfterHooks(config.plugins, config, config.hooks, 'afterAccountDelete', ctx, result),
48
+ afterAccountDeleteFailure: async (ctx, failure) => runAfterHooks(config.plugins, config, config.hooks, 'afterAccountDeleteFailure', ctx, failure)
49
+ };
50
+ }
51
+ export function createPluginRunner(config) {
52
+ validatePlugins(config);
53
+ const hooks = composePluginHooks(config);
54
+ return {
55
+ routes: composePluginRoutes(config, hooks),
56
+ hooks
57
+ };
58
+ }
59
+ async function runBeforeHooks(plugins, config, configHooks, hookName, ctx, input) {
60
+ let current = input;
61
+ for (const plugin of plugins) {
62
+ const hook = plugin.hooks?.[hookName];
63
+ if (!hook) {
64
+ continue;
65
+ }
66
+ let result;
67
+ try {
68
+ result = await hook?.({ ...ctx, config: ctx.config, pluginName: plugin.name }, current ?? input);
69
+ }
70
+ catch (error) {
71
+ await emitAuthEvent(config, {
72
+ type: 'authfn.plugin.failed',
73
+ requestId: eventRequestId(ctx.request),
74
+ actorId: ctx.actorId,
75
+ pluginName: plugin.name,
76
+ hookName,
77
+ outcome: 'aborted',
78
+ metadata: {
79
+ errorCode: readErrorCode(error),
80
+ retriable: readRetryable(error)
81
+ }
82
+ });
83
+ if (isAuthFnError(error)) {
84
+ throw error;
85
+ }
86
+ throw new AuthFnPluginAbortedError(`${plugin.name}.${hookName} aborted authfn execution`, {
87
+ pluginName: plugin.name,
88
+ hookName,
89
+ actorId: ctx.actorId
90
+ });
91
+ }
92
+ if (result !== undefined) {
93
+ current = result;
94
+ }
95
+ }
96
+ const configHook = configHooks?.[hookName];
97
+ if (!configHook) {
98
+ return current;
99
+ }
100
+ let result;
101
+ try {
102
+ result = await configHook?.({ ...ctx, config: ctx.config }, current ?? input);
103
+ }
104
+ catch (error) {
105
+ await emitAuthEvent(config, {
106
+ type: 'authfn.plugin.failed',
107
+ requestId: eventRequestId(ctx.request),
108
+ actorId: ctx.actorId,
109
+ pluginName: 'config',
110
+ hookName,
111
+ outcome: 'aborted',
112
+ metadata: {
113
+ errorCode: readErrorCode(error),
114
+ retriable: readRetryable(error)
115
+ }
116
+ });
117
+ if (isAuthFnError(error)) {
118
+ throw error;
119
+ }
120
+ throw new AuthFnPluginAbortedError(`config.${hookName} aborted authfn execution`, {
121
+ pluginName: 'config',
122
+ hookName,
123
+ actorId: ctx.actorId
124
+ });
125
+ }
126
+ return result ?? current;
127
+ }
128
+ async function runAfterHooks(plugins, config, configHooks, hookName, ctx, payload) {
129
+ for (const plugin of plugins) {
130
+ const hook = plugin.hooks?.[hookName];
131
+ if (!hook) {
132
+ continue;
133
+ }
134
+ try {
135
+ await hook({ ...ctx, config: ctx.config, pluginName: plugin.name }, payload);
136
+ }
137
+ catch (error) {
138
+ const failurePolicy = getAfterHookFailurePolicy(plugin, hookName);
139
+ await emitAuthEvent(config, {
140
+ type: 'authfn.plugin.failed',
141
+ requestId: eventRequestId(ctx.request),
142
+ actorId: ctx.actorId,
143
+ pluginName: plugin.name,
144
+ hookName,
145
+ outcome: failurePolicy === 'fail' ? 'aborted' : 'observed',
146
+ metadata: {
147
+ errorCode: readErrorCode(error),
148
+ retriable: readRetryable(error)
149
+ }
150
+ });
151
+ if (failurePolicy === 'fail') {
152
+ if (isAuthFnError(error)) {
153
+ throw error;
154
+ }
155
+ throw new AuthFnPluginAbortedError(`${plugin.name}.${hookName} aborted authfn execution`, {
156
+ pluginName: plugin.name,
157
+ hookName,
158
+ actorId: ctx.actorId,
159
+ cause: error instanceof Error ? error.message : String(error)
160
+ });
161
+ }
162
+ }
163
+ }
164
+ const configHook = configHooks?.[hookName];
165
+ if (!configHook) {
166
+ return;
167
+ }
168
+ try {
169
+ await configHook({ ...ctx, config: ctx.config }, payload);
170
+ }
171
+ catch (error) {
172
+ await emitAuthEvent(config, {
173
+ type: 'authfn.plugin.failed',
174
+ requestId: eventRequestId(ctx.request),
175
+ actorId: ctx.actorId,
176
+ pluginName: 'config',
177
+ hookName,
178
+ outcome: 'observed',
179
+ metadata: {
180
+ errorCode: readErrorCode(error),
181
+ retriable: readRetryable(error)
182
+ }
183
+ });
184
+ }
185
+ }
186
+ function getAfterHookFailurePolicy(plugin, hookName) {
187
+ return plugin.hookFailurePolicy?.[hookName] ?? 'observe';
188
+ }
189
+ function isAuthFnError(error) {
190
+ if (error instanceof AuthFnErrorClass) {
191
+ return true;
192
+ }
193
+ return Boolean(error
194
+ && typeof error === 'object'
195
+ && Object.prototype.hasOwnProperty.call(error, 'code')
196
+ && typeof error.code === 'string'
197
+ && Object.prototype.hasOwnProperty.call(error, 'status')
198
+ && typeof error.status === 'number');
199
+ }
200
+ function readErrorCode(error) {
201
+ return isAuthFnError(error) ? error.code : 'AUTHFN_INTERNAL_ERROR';
202
+ }
203
+ function readRetryable(error) {
204
+ return isAuthFnError(error) ? Boolean(error.retryable) : false;
205
+ }
206
+ //# sourceMappingURL=plugin-runner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin-runner.js","sourceRoot":"","sources":["../src/plugin-runner.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,WAAW,IAAI,gBAAgB,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC7F,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAExE,MAAM,iBAAiB,GAAG;IACxB,kBAAkB;IAClB,oBAAoB;IACpB,qBAAqB;IACrB,kBAAkB;IAClB,qBAAqB;CACb,CAAC;AAEX,MAAM,gBAAgB,GAAG;IACvB,iBAAiB;IACjB,mBAAmB;IACnB,oBAAoB;IACpB,oBAAoB;IACpB,oBAAoB;IACpB,2BAA2B;CACnB,CAAC;AAUX,MAAM,UAAU,0BAA0B,CACxC,MAA2B,EAC3B,QAA8B,MAAM,CAAC,KAAK,IAAI,EAAE;IAEhD,OAAO;QACL,MAAM;QACN,SAAS,EAAE,MAAM,CAAC,SA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BAAiB,EAAE,CAAC,QAAQ,CAAC,IAAI,SAAS,CAAC;AAC3D,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACnC,IAAI,KAAK,YAAY,gBAAgB,EAAE,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,OAAO,CACZ,KAAK;WACA,OAAO,KAAK,KAAK,QAAQ;WACzB,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,EAAE,MAAM,CAAC;WACnD,OAAQ,KAA4B,CAAC,IAAI,KAAK,QAAQ;WACtD,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,EAAE,QAAQ,CAAC;WACrD,OAAQ,KAA8B,CAAC,MAAM,KAAK,QAAQ,CAChE,CAAC;AACJ,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,uBAAuB,CAAC;AACrE,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;AACjE,CAAC"}
@@ -0,0 +1,205 @@
1
+ import type { ConditionalKVStoreAdapter, TableSchema } from '@superfunctions/db';
2
+ import type { ObservabilityInput } from '@superfunctions/observability';
3
+ import type { AuthFnPlugin } from './types.js';
4
+ import type { AuthFnCookieConfig, AuthFnDeliveryMessageResolver, AuthFnPasswordCompromiseChecker, AuthFnEnvironment, AuthFnDeliveryProvider, AuthFnEvent } from './types.js';
5
+ export interface AuthFnBundledPluginConfig {
6
+ schema?: TableSchema[];
7
+ }
8
+ export interface PasswordPluginConfig extends AuthFnBundledPluginConfig {
9
+ compromisedPasswordChecker?: AuthFnPasswordCompromiseChecker;
10
+ requireEmailVerifiedForSignIn?: boolean;
11
+ /** @deprecated Configure password OTP delivery through pluginRuntime.password.otp. */
12
+ otp?: Partial<EmailOtpPluginRuntimeConfig>;
13
+ }
14
+ export interface PasswordPluginRuntimeConfig {
15
+ /** OTP delivery and challenge settings used by password sign-up, sign-in, and reset flows. */
16
+ otp?: EmailOtpPluginRuntimeConfig;
17
+ }
18
+ export interface EmailOtpPluginConfig extends AuthFnBundledPluginConfig {
19
+ }
20
+ export interface EmailOtpPluginRuntimeConfig {
21
+ /** Provider responsible for sending OTP challenges and receiving OTP lifecycle events. */
22
+ delivery: AuthFnDeliveryProvider;
23
+ /** Optional resolver used to customize the OTP message before it is passed to the delivery provider. */
24
+ message?: AuthFnDeliveryMessageResolver;
25
+ /** Optional code generator for tests or custom OTP formats; defaults to the built-in numeric generator. */
26
+ codeGenerator?: () => string;
27
+ /** Clock source used for challenge creation and expiry checks; primarily useful for tests. */
28
+ now?: () => Date;
29
+ /** Number of seconds before an OTP challenge expires. */
30
+ challengeTtlSeconds?: number;
31
+ /** Maximum verification attempts allowed before a challenge is rejected. */
32
+ maxAttempts?: number;
33
+ }
34
+ export interface ApiKeyPluginConfig extends AuthFnBundledPluginConfig {
35
+ secretPrefix?: string;
36
+ }
37
+ export interface ApiKeyPluginRuntimeConfig {
38
+ /** Clock source used for API key timestamps and expiry checks; primarily useful for tests. */
39
+ now?: () => Date;
40
+ }
41
+ export interface TwoFactorPluginConfig extends AuthFnBundledPluginConfig {
42
+ }
43
+ export interface TwoFactorPluginRuntimeConfig {
44
+ /** Issuer name displayed by authenticator apps for generated TOTP enrollments. */
45
+ issuer?: string;
46
+ /** Clock source used for TOTP challenge creation and verification; primarily useful for tests. */
47
+ now?: () => Date;
48
+ /** Number of seconds before a two-factor challenge expires. */
49
+ challengeTtlSeconds?: number;
50
+ /** Number of recovery codes generated for each confirmed enrollment. */
51
+ recoveryCodeCount?: number;
52
+ /** Number of digits in generated TOTP codes. */
53
+ digits?: number;
54
+ /** TOTP time-step duration in seconds. */
55
+ periodSeconds?: number;
56
+ /** Number of adjacent TOTP windows accepted during verification. */
57
+ window?: number;
58
+ /** Key reference passed to encryptionKeyResolver when encrypting two-factor secrets. */
59
+ encryptionKeyRef?: string;
60
+ /** Resolves the encryption key used for two-factor secret storage. */
61
+ encryptionKeyResolver?: (keyRef: string) => Promise<Buffer> | Buffer;
62
+ }
63
+ export interface NativeHandoffPluginConfig extends AuthFnBundledPluginConfig {
64
+ codeTtlSeconds?: number;
65
+ }
66
+ export interface NativeHandoffPluginRuntimeConfig {
67
+ /** Clock source used for native handoff code timestamps and expiry checks; primarily useful for tests. */
68
+ now?: () => Date;
69
+ }
70
+ export interface AuthFnMultiRegionRegionConfig {
71
+ regionId: string;
72
+ authority: string;
73
+ domain?: string;
74
+ hosts?: string[];
75
+ issuer?: string;
76
+ baseUrl?: string;
77
+ cookie?: Partial<AuthFnCookieConfig>;
78
+ oauth?: AuthFnEnvironment['oauth'];
79
+ }
80
+ export interface AuthFnMultiRegionLookupInput {
81
+ identifier: string;
82
+ request?: Request;
83
+ environment: AuthFnEnvironment;
84
+ }
85
+ export interface AuthFnMultiRegionLookupResult {
86
+ userId?: string;
87
+ regionId: string;
88
+ authority: string;
89
+ domain?: string;
90
+ }
91
+ export interface AuthFnMultiRegionRegistrationInput {
92
+ userId: string;
93
+ primaryEmail?: string;
94
+ regionId: string;
95
+ authority: string;
96
+ domain?: string;
97
+ request?: Request;
98
+ environment: AuthFnEnvironment;
99
+ }
100
+ export interface AuthFnRegionLookupRecord {
101
+ identifier: string;
102
+ userId?: string;
103
+ regionId: string;
104
+ authority: string;
105
+ domain?: string;
106
+ createdAt: Date | string;
107
+ updatedAt: Date | string;
108
+ }
109
+ export type AuthFnIdentityPlacementState = 'active' | 'moving' | 'deleting' | 'tombstoned';
110
+ /**
111
+ * Canonical ownership record for an AuthFn identity. The directory owns only
112
+ * placement metadata; cell destinations remain private to the cell registry.
113
+ */
114
+ export interface AuthFnIdentityPlacement {
115
+ identityKey: string;
116
+ regionId: string;
117
+ epoch: number;
118
+ state: AuthFnIdentityPlacementState;
119
+ movingToRegionId?: string;
120
+ previousRegionId?: string;
121
+ updatedAt: Date | string;
122
+ }
123
+ export interface AuthFnIdentityPlacementDirectoryAdapter {
124
+ /** Strongly consistent with every successful claim and epoch transition. */
125
+ get(identityKey: string): Promise<AuthFnIdentityPlacement | null>;
126
+ /** Globally atomic across every gateway writer for the same identity key. */
127
+ putIfAbsent(placement: AuthFnIdentityPlacement): Promise<{
128
+ inserted: boolean;
129
+ existing?: AuthFnIdentityPlacement;
130
+ }>;
131
+ /** Globally atomic across every writer and fenced by both epoch and state. */
132
+ compareAndSet(input: {
133
+ identityKey: string;
134
+ expectedEpoch: number;
135
+ expectedState: AuthFnIdentityPlacementState;
136
+ placement: AuthFnIdentityPlacement;
137
+ }): Promise<{
138
+ updated: boolean;
139
+ existing?: AuthFnIdentityPlacement;
140
+ }>;
141
+ }
142
+ export interface AuthFnRoutingSigningKey {
143
+ keyId: string;
144
+ secret: string | Uint8Array;
145
+ }
146
+ export interface AuthFnRoutingKeyring {
147
+ active: AuthFnRoutingSigningKey;
148
+ /** Verification-only keys retained during rotation. */
149
+ previous?: AuthFnRoutingSigningKey[];
150
+ }
151
+ export interface AuthFnRoutingReplayStore {
152
+ /** Atomically claims a nonce until its expiry. False means replay. */
153
+ claim(nonce: string, expiresAt: number): Promise<boolean>;
154
+ }
155
+ interface AuthFnCanonicalRoutingBase {
156
+ /** Stable public issuer/base URL used for discovery, OAuth, and cookies. */
157
+ publicAuthority?: string;
158
+ /** Canonical cookie policy. In gateway mode this must not vary by cell. */
159
+ canonicalCookie?: Partial<AuthFnCookieConfig>;
160
+ /** Canonical OAuth policy merged independently of the execution cell. */
161
+ canonicalOAuth?: AuthFnEnvironment['oauth'];
162
+ }
163
+ export interface AuthFnDirectRoutingConfig extends AuthFnCanonicalRoutingBase {
164
+ mode: 'direct';
165
+ placementDirectory?: never;
166
+ identityKeyForIdentifier?: never;
167
+ identityKeyForUserId?: never;
168
+ cell?: never;
169
+ }
170
+ export interface AuthFnGatewayRoutingConfig extends AuthFnCanonicalRoutingBase {
171
+ mode: 'gateway';
172
+ publicAuthority: string;
173
+ /** Required in gateway mode on both the gateway and regional cells. */
174
+ placementDirectory: AuthFnIdentityPlacementDirectoryAdapter;
175
+ /** Maps normalized public identifiers to the same stable key used by the gateway. */
176
+ identityKeyForIdentifier: (identifier: string) => string;
177
+ /** Resolves persisted user IDs to the exact stable placement key used by the gateway. */
178
+ identityKeyForUserId: (userId: string) => string | Promise<string>;
179
+ /** Required by a regional cell to validate gateway assertions. */
180
+ cell?: {
181
+ regionId: string;
182
+ audience: string;
183
+ keyring: AuthFnRoutingKeyring;
184
+ replayStore: AuthFnRoutingReplayStore;
185
+ clockSkewSeconds?: number;
186
+ };
187
+ }
188
+ export type AuthFnCanonicalRoutingConfig = AuthFnDirectRoutingConfig | AuthFnGatewayRoutingConfig;
189
+ export interface MultiRegionPluginConfig extends AuthFnBundledPluginConfig {
190
+ }
191
+ export interface MultiRegionPluginRuntimeConfig {
192
+ /** Region definitions available to the multi-region resolver and routing plugin. */
193
+ regions?: AuthFnMultiRegionRegionConfig[];
194
+ /** Region ID used when no request host or identifier lookup selects another region. */
195
+ defaultRegionId?: string;
196
+ /** Store used to look up and register the region that owns a user identifier. */
197
+ lookupStore?: ConditionalKVStoreAdapter;
198
+ /** Observability sink for multi-region lookup, registration, and conflict events. */
199
+ observability?: ObservabilityInput<AuthFnEvent>;
200
+ /** Canonical-gateway routing. Omit (or use direct) for legacy regional clients. */
201
+ routing?: AuthFnCanonicalRoutingConfig;
202
+ }
203
+ export type AuthFnPluginFactory<TConfig extends AuthFnBundledPluginConfig> = (config?: TConfig) => AuthFnPlugin;
204
+ export {};
205
+ //# sourceMappingURL=plugin-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin-types.d.ts","sourceRoot":"","sources":["../src/plugin-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,WAAW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plugin-types.js","sourceRoot":"","sources":["../src/plugin-types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,7 @@
1
+ import type { TableSchema } from '@superfunctions/db';
2
+ import type { AuthFnConfig, AuthFnSchemaDefinition } from './types.js';
3
+ export declare const AUTHFN_SCHEMA_VERSION = 2;
4
+ export declare function getSchema(config: AuthFnConfig): AuthFnSchemaDefinition;
5
+ export declare function createCoreTables(): TableSchema[];
6
+ export declare function normalizeTableSchema(table: TableSchema): TableSchema;
7
+ //# sourceMappingURL=schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAGtD,OAAO,KAAK,EAAE,YAAY,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAEvE,eAAO,MAAM,qBAAqB,IAAI,CAAC;AAEvC,wBAAgB,SAAS,CAAC,MAAM,EAAE,YAAY,GAAG,sBAAsB,CAetE;AAED,wBAAgB,gBAAgB,IAAI,WAAW,EAAE,CA+DhD;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,WAAW,GAAG,WAAW,CAepE"}
package/dist/schema.js ADDED
@@ -0,0 +1,127 @@
1
+ import { AUTHFN_LEGACY_USER_REFERENCE_MAX_LENGTH } from './core/limits.js';
2
+ import { AuthFnConfigError, AuthFnConflictError } from './types.js';
3
+ export const AUTHFN_SCHEMA_VERSION = 2;
4
+ export function getSchema(config) {
5
+ if (!Array.isArray(config.plugins)) {
6
+ throw new AuthFnConfigError('authfn plugins must be provided as an array');
7
+ }
8
+ const baseTables = createCoreTables();
9
+ const pluginTables = config.plugins.flatMap((plugin) => plugin.schema?.(config) ?? []);
10
+ const orderedTables = [...baseTables, ...pluginTables].map((table) => normalizeTableSchema(table));
11
+ assertNoTableConflicts(orderedTables);
12
+ return {
13
+ version: AUTHFN_SCHEMA_VERSION,
14
+ schemas: orderedTables
15
+ };
16
+ }
17
+ export function createCoreTables() {
18
+ return [
19
+ {
20
+ modelName: 'users',
21
+ fields: {
22
+ id: {
23
+ type: 'string',
24
+ required: true,
25
+ fieldName: 'id',
26
+ maxLength: AUTHFN_LEGACY_USER_REFERENCE_MAX_LENGTH
27
+ },
28
+ primaryEmail: { type: 'string', required: false, fieldName: 'primary_email', maxLength: 255 },
29
+ emailVerifiedAt: { type: 'date', required: false, fieldName: 'email_verified_at' },
30
+ metadata: { type: 'json', required: false, fieldName: 'metadata' },
31
+ createdAt: { type: 'date', required: true, fieldName: 'created_at' },
32
+ updatedAt: { type: 'date', required: true, fieldName: 'updated_at' }
33
+ },
34
+ indexes: [
35
+ {
36
+ name: 'idx_authfn_users_primary_email',
37
+ fields: ['primaryEmail'],
38
+ unique: true
39
+ }
40
+ ]
41
+ },
42
+ {
43
+ modelName: 'sessions',
44
+ fields: {
45
+ id: { type: 'string', required: true, fieldName: 'id', maxLength: 255 },
46
+ userId: {
47
+ type: 'string',
48
+ required: true,
49
+ fieldName: 'user_id',
50
+ maxLength: AUTHFN_LEGACY_USER_REFERENCE_MAX_LENGTH,
51
+ references: { model: 'users', field: 'id', onDelete: 'cascade' }
52
+ },
53
+ tokenHash: { type: 'string', required: true, fieldName: 'token_hash', maxLength: 255 },
54
+ csrfHash: { type: 'string', required: false, fieldName: 'csrf_hash' },
55
+ methods: { type: 'json', required: true, fieldName: 'methods' },
56
+ metadata: { type: 'json', required: false, fieldName: 'metadata' },
57
+ expiresAt: { type: 'date', required: true, fieldName: 'expires_at' },
58
+ revokedAt: { type: 'date', required: false, fieldName: 'revoked_at' },
59
+ createdAt: { type: 'date', required: true, fieldName: 'created_at' },
60
+ updatedAt: { type: 'date', required: true, fieldName: 'updated_at' },
61
+ lastAuthenticatedAt: { type: 'date', required: false, fieldName: 'last_authenticated_at' }
62
+ },
63
+ indexes: [
64
+ {
65
+ name: 'idx_authfn_sessions_expires_at',
66
+ fields: ['expiresAt']
67
+ },
68
+ {
69
+ name: 'idx_authfn_sessions_token_hash',
70
+ fields: ['tokenHash'],
71
+ unique: true
72
+ },
73
+ {
74
+ name: 'idx_authfn_sessions_user_id_created_at',
75
+ fields: ['userId', 'createdAt']
76
+ }
77
+ ]
78
+ }
79
+ ];
80
+ }
81
+ export function normalizeTableSchema(table) {
82
+ return {
83
+ ...table,
84
+ fields: Object.fromEntries(Object.entries(table.fields)
85
+ .sort(([left], [right]) => left.localeCompare(right))
86
+ .map(([fieldName, field]) => [fieldName, normalizeFieldSchema(field)])),
87
+ indexes: table.indexes
88
+ ? [...table.indexes].sort((left, right) => left.name.localeCompare(right.name))
89
+ : undefined,
90
+ constraints: table.constraints
91
+ ? [...table.constraints].sort((left, right) => left.name.localeCompare(right.name))
92
+ : undefined
93
+ };
94
+ }
95
+ function normalizeFieldSchema(field) {
96
+ if (field.type !== 'date' && field.type !== 'datetime') {
97
+ return field;
98
+ }
99
+ return {
100
+ ...field,
101
+ dateValueType: field.dateValueType ?? 'date',
102
+ dateStorageType: field.dateStorageType ?? 'timestamptz'
103
+ };
104
+ }
105
+ function assertNoTableConflicts(tables) {
106
+ const seenTableNames = new Set();
107
+ for (const table of tables) {
108
+ if (seenTableNames.has(table.modelName)) {
109
+ throw new AuthFnConflictError(`duplicate authfn table schema: ${table.modelName}`, {
110
+ tableName: table.modelName
111
+ });
112
+ }
113
+ seenTableNames.add(table.modelName);
114
+ const seenColumnNames = new Set();
115
+ for (const [fieldName, fieldSchema] of Object.entries(table.fields)) {
116
+ const columnName = fieldSchema.fieldName ?? fieldName;
117
+ if (seenColumnNames.has(columnName)) {
118
+ throw new AuthFnConflictError(`duplicate authfn column mapping: ${table.modelName}.${columnName}`, {
119
+ tableName: table.modelName,
120
+ columnName
121
+ });
122
+ }
123
+ seenColumnNames.add(columnName);
124
+ }
125
+ }
126
+ }
127
+ //# sourceMappingURL=schema.js.map