@venturekit/auth 0.0.38 → 0.0.39

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 (41) hide show
  1. package/README.md +108 -0
  2. package/dist/migrations/vk_auth_004_api_keys.sql +38 -0
  3. package/dist/migrations/vk_auth_005_invitations.sql +37 -0
  4. package/dist/server/api-keys.d.ts +123 -0
  5. package/dist/server/api-keys.d.ts.map +1 -0
  6. package/dist/server/api-keys.js +209 -0
  7. package/dist/server/api-keys.js.map +1 -0
  8. package/dist/server/federated-routes.d.ts +18 -1
  9. package/dist/server/federated-routes.d.ts.map +1 -1
  10. package/dist/server/federated-routes.js +14 -2
  11. package/dist/server/federated-routes.js.map +1 -1
  12. package/dist/server/federated.d.ts +65 -5
  13. package/dist/server/federated.d.ts.map +1 -1
  14. package/dist/server/federated.js +44 -12
  15. package/dist/server/federated.js.map +1 -1
  16. package/dist/server/impersonation.d.ts +114 -0
  17. package/dist/server/impersonation.d.ts.map +1 -0
  18. package/dist/server/impersonation.js +173 -0
  19. package/dist/server/impersonation.js.map +1 -0
  20. package/dist/server/index.d.ts +9 -1
  21. package/dist/server/index.d.ts.map +1 -1
  22. package/dist/server/index.js +8 -0
  23. package/dist/server/index.js.map +1 -1
  24. package/dist/server/invitations.d.ts +135 -0
  25. package/dist/server/invitations.d.ts.map +1 -0
  26. package/dist/server/invitations.js +241 -0
  27. package/dist/server/invitations.js.map +1 -0
  28. package/dist/server/passkeys.d.ts +86 -0
  29. package/dist/server/passkeys.d.ts.map +1 -0
  30. package/dist/server/passkeys.js +200 -0
  31. package/dist/server/passkeys.js.map +1 -0
  32. package/dist/server/sign-up.d.ts +16 -4
  33. package/dist/server/sign-up.d.ts.map +1 -1
  34. package/dist/server/sign-up.js +38 -9
  35. package/dist/server/sign-up.js.map +1 -1
  36. package/dist/server/store/postgres.d.ts.map +1 -1
  37. package/dist/server/store/postgres.js +13 -4
  38. package/dist/server/store/postgres.js.map +1 -1
  39. package/package.json +6 -6
  40. package/src/migrations/vk_auth_004_api_keys.sql +38 -0
  41. package/src/migrations/vk_auth_005_invitations.sql +37 -0
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Passkeys (WebAuthn) — enrolment and sign-in against a Cognito pool that
3
+ * declares `auth[].passkeys` (which turns on the choice-based `USER_AUTH`
4
+ * flow and binds the pool to a relying-party domain).
5
+ *
6
+ * Two flows, each a pair of calls around one browser round-trip:
7
+ *
8
+ * **Enrol** (signed-in user, from a settings page):
9
+ * ```ts
10
+ * // POST /auth/passkeys/begin → options for navigator.credentials.create()
11
+ * const options = await beginPasskeyRegistration(accessToken);
12
+ * // browser: const cred = await navigator.credentials.create({ publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(options) });
13
+ * // POST /auth/passkeys/complete { credential: cred.toJSON() }
14
+ * await completePasskeyRegistration(accessToken, body.credential);
15
+ * ```
16
+ *
17
+ * **Sign in** (no password):
18
+ * ```ts
19
+ * // POST /auth/passkeys/signin/begin { email } → options for navigator.credentials.get()
20
+ * const { session, options } = await beginPasskeySignIn(email);
21
+ * // browser: const cred = await navigator.credentials.get({ publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(options) });
22
+ * // POST /auth/passkeys/signin/complete { email, session, credential: cred.toJSON() }
23
+ * const tokens = await completePasskeySignIn({ email, session, credential });
24
+ * ```
25
+ *
26
+ * `session` is Cognito's opaque, short-lived challenge session; pass it
27
+ * back untouched. The credential JSON is the W3C `toJSON()` shape —
28
+ * this module does not parse it, Cognito verifies it.
29
+ *
30
+ * Requires the `essentials` or `plus` feature plan; with `lite`, Cognito
31
+ * answers `InvalidParameterException`, surfaced as `passkeys_unavailable`.
32
+ */
33
+ import { CompleteWebAuthnRegistrationCommand, DeleteWebAuthnCredentialCommand, InitiateAuthCommand, ListWebAuthnCredentialsCommand, RespondToAuthChallengeCommand, StartWebAuthnRegistrationCommand, } from '@aws-sdk/client-cognito-identity-provider';
34
+ import { loadAuthServerConfig } from './config.js';
35
+ import { getCognitoClient } from './cognito-client.js';
36
+ import { AuthError, mapProviderError } from './errors.js';
37
+ import { extractSignInTokens } from './tokens.js';
38
+ function isPlanError(err) {
39
+ const name = err.name;
40
+ const message = String(err.message ?? '');
41
+ return name === 'InvalidParameterException' && /web ?authn|passkey|feature plan|user_auth/i.test(message);
42
+ }
43
+ function mapPasskeyError(err, fallback) {
44
+ if (isPlanError(err)) {
45
+ return new AuthError('passkeys_unavailable', 'Passkeys are not enabled on this user pool (declare auth[].passkeys on an essentials/plus plan)', 501);
46
+ }
47
+ return mapProviderError(err, fallback);
48
+ }
49
+ // ---------------------------------------------------------------------------
50
+ // Enrolment (authenticated)
51
+ // ---------------------------------------------------------------------------
52
+ /**
53
+ * Start enrolling a passkey for the signed-in user. Returns the creation
54
+ * options JSON for `navigator.credentials.create()` (via
55
+ * `PublicKeyCredential.parseCreationOptionsFromJSON`).
56
+ */
57
+ export async function beginPasskeyRegistration(accessToken, config = loadAuthServerConfig()) {
58
+ const client = getCognitoClient(config.region, config.endpoint);
59
+ try {
60
+ const res = await client.send(new StartWebAuthnRegistrationCommand({ AccessToken: accessToken }));
61
+ const options = res.CredentialCreationOptions;
62
+ if (!options) {
63
+ throw new AuthError('passkey_registration_failed', 'Identity provider returned no credential creation options', 500);
64
+ }
65
+ return options;
66
+ }
67
+ catch (err) {
68
+ if (err instanceof AuthError)
69
+ throw err;
70
+ throw mapPasskeyError(err, 'passkey_registration_failed');
71
+ }
72
+ }
73
+ /**
74
+ * Finish enrolment with the credential the browser created
75
+ * (`PublicKeyCredential.toJSON()` output, passed through unchanged).
76
+ */
77
+ export async function completePasskeyRegistration(accessToken, credential, config = loadAuthServerConfig()) {
78
+ if (!credential || typeof credential !== 'object') {
79
+ throw new AuthError('invalid_passkey_credential', 'credential must be the PublicKeyCredential JSON', 400);
80
+ }
81
+ const client = getCognitoClient(config.region, config.endpoint);
82
+ try {
83
+ await client.send(new CompleteWebAuthnRegistrationCommand({
84
+ AccessToken: accessToken,
85
+ Credential: credential,
86
+ }));
87
+ }
88
+ catch (err) {
89
+ throw mapPasskeyError(err, 'passkey_registration_failed');
90
+ }
91
+ }
92
+ /** The signed-in user's enrolled passkeys, for a "manage devices" screen. */
93
+ export async function listPasskeys(accessToken, config = loadAuthServerConfig()) {
94
+ const client = getCognitoClient(config.region, config.endpoint);
95
+ const out = [];
96
+ let nextToken;
97
+ try {
98
+ do {
99
+ const res = await client.send(new ListWebAuthnCredentialsCommand({ AccessToken: accessToken, MaxResults: 20, NextToken: nextToken }));
100
+ for (const c of res.Credentials ?? []) {
101
+ if (!c.CredentialId)
102
+ continue;
103
+ out.push({
104
+ credentialId: c.CredentialId,
105
+ ...(c.FriendlyCredentialName ? { friendlyName: c.FriendlyCredentialName } : {}),
106
+ ...(c.RelyingPartyId ? { relyingPartyId: c.RelyingPartyId } : {}),
107
+ ...(c.AuthenticatorAttachment ? { authenticatorAttachment: c.AuthenticatorAttachment } : {}),
108
+ ...(c.AuthenticatorTransports ? { transports: c.AuthenticatorTransports } : {}),
109
+ ...(c.CreatedAt ? { createdAt: new Date(c.CreatedAt) } : {}),
110
+ });
111
+ }
112
+ nextToken = res.NextToken;
113
+ } while (nextToken);
114
+ }
115
+ catch (err) {
116
+ throw mapPasskeyError(err, 'passkey_list_failed');
117
+ }
118
+ return out;
119
+ }
120
+ /** Remove one enrolled passkey (the user's own — the access token scopes it). */
121
+ export async function deletePasskey(accessToken, credentialId, config = loadAuthServerConfig()) {
122
+ const client = getCognitoClient(config.region, config.endpoint);
123
+ try {
124
+ await client.send(new DeleteWebAuthnCredentialCommand({ AccessToken: accessToken, CredentialId: credentialId }));
125
+ }
126
+ catch (err) {
127
+ throw mapPasskeyError(err, 'passkey_delete_failed');
128
+ }
129
+ }
130
+ /**
131
+ * Ask Cognito for a WebAuthn challenge for `username` (email). Uses the
132
+ * choice-based `USER_AUTH` flow with `PREFERRED_CHALLENGE=WEB_AUTHN`.
133
+ *
134
+ * Throws `passkey_not_available` (400) when the user has no passkey
135
+ * enrolled and Cognito offers other factors instead — the app then falls
136
+ * back to the password form.
137
+ */
138
+ export async function beginPasskeySignIn(username, config = loadAuthServerConfig()) {
139
+ const client = getCognitoClient(config.region, config.endpoint);
140
+ let res;
141
+ try {
142
+ res = await client.send(new InitiateAuthCommand({
143
+ ClientId: config.appClientId,
144
+ AuthFlow: 'USER_AUTH',
145
+ AuthParameters: {
146
+ USERNAME: username.trim().toLowerCase(),
147
+ PREFERRED_CHALLENGE: 'WEB_AUTHN',
148
+ },
149
+ }));
150
+ }
151
+ catch (err) {
152
+ throw mapPasskeyError(err, 'auth_failed');
153
+ }
154
+ const raw = res.ChallengeParameters?.['CREDENTIAL_REQUEST_OPTIONS'];
155
+ if (res.ChallengeName !== 'WEB_AUTHN' || !raw || !res.Session) {
156
+ throw new AuthError('passkey_not_available', res.ChallengeName === 'SELECT_CHALLENGE'
157
+ ? 'No passkey is enrolled for this account; sign in another way'
158
+ : `Identity provider did not offer a passkey challenge (${res.ChallengeName ?? 'none'})`, 400);
159
+ }
160
+ let options;
161
+ try {
162
+ options = JSON.parse(raw);
163
+ }
164
+ catch {
165
+ throw new AuthError('auth_failed', 'Identity provider returned malformed credential request options', 500);
166
+ }
167
+ return { session: res.Session, options };
168
+ }
169
+ /** Finish the passkey sign-in and mint tokens — same shape as `signInWithPassword`. */
170
+ export async function completePasskeySignIn(input, config = loadAuthServerConfig()) {
171
+ if (!input.credential || typeof input.credential !== 'object') {
172
+ throw new AuthError('invalid_passkey_credential', 'credential must be the PublicKeyCredential JSON', 400);
173
+ }
174
+ if (!input.session) {
175
+ throw new AuthError('invalid_passkey_credential', 'session is required', 400);
176
+ }
177
+ const client = getCognitoClient(config.region, config.endpoint);
178
+ let res;
179
+ try {
180
+ res = await client.send(new RespondToAuthChallengeCommand({
181
+ ClientId: config.appClientId,
182
+ ChallengeName: 'WEB_AUTHN',
183
+ Session: input.session,
184
+ ChallengeResponses: {
185
+ USERNAME: input.username.trim().toLowerCase(),
186
+ CREDENTIAL: JSON.stringify(input.credential),
187
+ },
188
+ }));
189
+ }
190
+ catch (err) {
191
+ throw mapPasskeyError(err, 'auth_failed');
192
+ }
193
+ if (res.ChallengeName) {
194
+ // A pool with MFA required may chain a second factor; the existing
195
+ // challenge helpers handle that from here.
196
+ throw new AuthError('auth_challenge_required', `Identity provider requires challenge: ${res.ChallengeName}.`, 400);
197
+ }
198
+ return extractSignInTokens(res.AuthenticationResult);
199
+ }
200
+ //# sourceMappingURL=passkeys.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"passkeys.js","sourceRoot":"","sources":["../../src/server/passkeys.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,EACL,mCAAmC,EACnC,+BAA+B,EAC/B,mBAAmB,EACnB,8BAA8B,EAC9B,6BAA6B,EAC7B,gCAAgC,GAEjC,MAAM,2CAA2C,CAAC;AAEnD,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,mBAAmB,EAAqB,MAAM,aAAa,CAAC;AAiBrE,SAAS,WAAW,CAAC,GAAY;IAC/B,MAAM,IAAI,GAAI,GAAyB,CAAC,IAAI,CAAC;IAC7C,MAAM,OAAO,GAAG,MAAM,CAAE,GAA4B,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC;IACpE,OAAO,IAAI,KAAK,2BAA2B,IAAI,4CAA4C,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAC5G,CAAC;AAED,SAAS,eAAe,CAAC,GAAY,EAAE,QAAgB;IACrD,IAAI,WAAW,CAAC,GAAG,CAAC,EAAE,CAAC;QACrB,OAAO,IAAI,SAAS,CAClB,sBAAsB,EACtB,iGAAiG,EACjG,GAAG,CACJ,CAAC;IACJ,CAAC;IACD,OAA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,KAAK,QAAQ,EAAE,CAAC;QAC9D,MAAM,IAAI,SAAS,CAAC,4BAA4B,EAAE,iDAAiD,EAAE,GAAG,CAAC,CAAC;IAC5G,CAAC;IACD,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QACnB,MAAM,IAAI,SAAS,CAAC,4BAA4B,EAAE,qBAAqB,EAAE,GAAG,CAAC,CAAC;IAChF,CAAC;IACD,MAAM,MAAM,GAAG,gBAAgB,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;IAChE,IAAI,GAAG,CAAC;IACR,IAAI,CAAC;QACH,GAAG,GAAG,MAAM,MAAM,CAAC,IAAI,CACrB,IAAI,6BAA6B,CAAC;YAChC,QAAQ,EAAE,MAAM,CAAC,WAAW;YAC5B,aAAa,EAAE,WAAW;YAC1B,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,kBAAkB,EAAE;gBAClB,QAAQ,EAAE,KAAK,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE;gBAC7C,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,UAAU,CAAC;aAC7C;SACF,CAAC,CACH,CAAC;IACJ,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,eAAe,CAAC,GAAG,EAAE,aAAa,CAAC,CAAC;IAC5C,CAAC;IACD,IAAI,GAAG,CAAC,aAAa,EAAE,CAAC;QACtB,mEAAmE;QACnE,2CAA2C;QAC3C,MAAM,IAAI,SAAS,CAAC,yBAAyB,EAAE,yCAAyC,GAAG,CAAC,aAAa,GAAG,EAAE,GAAG,CAAC,CAAC;IACrH,CAAC;IACD,OAAO,mBAAmB,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;AACvD,CAAC"}
@@ -5,21 +5,29 @@
5
5
  * working "sign-up + immediate login" flow:
6
6
  *
7
7
  * 1. `SignUp` — create the user with email + password + standard
8
- * and custom attributes.
8
+ * attributes.
9
9
  * 2. `AdminConfirmSignUp` — skip the email-verification challenge
10
10
  * (the consumer's own flow is responsible for whatever real
11
11
  * verification ships before / after this).
12
12
  * 3. `AdminUpdateUserAttributes` — flip `email_verified=true` so
13
- * Cognito doesn't re-challenge on the next sign-in.
13
+ * Cognito doesn't re-challenge on the next sign-in, and apply
14
+ * {@link SignUpInput.customAttributes}.
15
+ *
16
+ * Custom attributes travel on the ADMIN call, never on `SignUp`: the
17
+ * app clients `@venturekit/infra` provisions may write standard
18
+ * attributes only (`custom:*` values such as `role` are authorization
19
+ * input, so a client that could write them would let any user promote
20
+ * themselves). Admin APIs bypass client write permissions.
14
21
  *
15
22
  * Steps 2-3 are gated by {@link SignUpInput.autoConfirm} (default
16
23
  * `true`). When the consumer wants the standard Cognito email-link
17
24
  * verification, set it to `false` and call `AdminConfirmSignUp`
18
- * yourself out-of-band.
25
+ * yourself out-of-band — custom attributes are then applied with a
26
+ * standalone `AdminUpdateUserAttributes` right after `SignUp`.
19
27
  *
20
28
  * In production the executing IAM principal needs
21
29
  * `cognito-idp:AdminConfirmSignUp` and
22
- * `cognito-idp:AdminUpdateUserAttributes` for steps 2-3.
30
+ * `cognito-idp:AdminUpdateUserAttributes`.
23
31
  * `cognito-local` accepts admin commands unauthenticated.
24
32
  */
25
33
  import type { AuthServerConfig } from './config.js';
@@ -41,6 +49,10 @@ export interface SignUpInput {
41
49
  * Custom attributes — keyed without the `custom:` prefix; the
42
50
  * helper prepends it. So `{ role: 'buyer' }` becomes
43
51
  * `{ Name: 'custom:role', Value: 'buyer' }`.
52
+ *
53
+ * Applied server-side via `AdminUpdateUserAttributes` (see the module
54
+ * docs). Values are trusted as-is: never forward a client-supplied
55
+ * `role` / `scopes` here without validating it first.
44
56
  */
45
57
  customAttributes?: Record<string, string>;
46
58
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"sign-up.d.ts","sourceRoot":"","sources":["../../src/server/sign-up.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GA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C,CAAC;IAC1C;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB;;;;;;;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;;;;;;;;GAQG;AACH,wBAAsB,UAAU,CAC9B,KAAK,EAAE,WAAW,EAClB,MAAM,GAAE,gBAAyC,GAChD,OAAO,CAAC,YAAY,CAAC,CAmFvB"}
@@ -5,21 +5,29 @@
5
5
  * working "sign-up + immediate login" flow:
6
6
  *
7
7
  * 1. `SignUp` — create the user with email + password + standard
8
- * and custom attributes.
8
+ * attributes.
9
9
  * 2. `AdminConfirmSignUp` — skip the email-verification challenge
10
10
  * (the consumer's own flow is responsible for whatever real
11
11
  * verification ships before / after this).
12
12
  * 3. `AdminUpdateUserAttributes` — flip `email_verified=true` so
13
- * Cognito doesn't re-challenge on the next sign-in.
13
+ * Cognito doesn't re-challenge on the next sign-in, and apply
14
+ * {@link SignUpInput.customAttributes}.
15
+ *
16
+ * Custom attributes travel on the ADMIN call, never on `SignUp`: the
17
+ * app clients `@venturekit/infra` provisions may write standard
18
+ * attributes only (`custom:*` values such as `role` are authorization
19
+ * input, so a client that could write them would let any user promote
20
+ * themselves). Admin APIs bypass client write permissions.
14
21
  *
15
22
  * Steps 2-3 are gated by {@link SignUpInput.autoConfirm} (default
16
23
  * `true`). When the consumer wants the standard Cognito email-link
17
24
  * verification, set it to `false` and call `AdminConfirmSignUp`
18
- * yourself out-of-band.
25
+ * yourself out-of-band — custom attributes are then applied with a
26
+ * standalone `AdminUpdateUserAttributes` right after `SignUp`.
19
27
  *
20
28
  * In production the executing IAM principal needs
21
29
  * `cognito-idp:AdminConfirmSignUp` and
22
- * `cognito-idp:AdminUpdateUserAttributes` for steps 2-3.
30
+ * `cognito-idp:AdminUpdateUserAttributes`.
23
31
  * `cognito-local` accepts admin commands unauthenticated.
24
32
  */
25
33
  import { AdminConfirmSignUpCommand, AdminUpdateUserAttributesCommand, SignUpCommand, } from '@aws-sdk/client-cognito-identity-provider';
@@ -39,7 +47,8 @@ export async function signUpUser(input, config = loadAuthServerConfig()) {
39
47
  const client = getCognitoClient(config.region, config.endpoint);
40
48
  const email = input.email.toLowerCase();
41
49
  const autoConfirm = input.autoConfirm ?? true;
42
- const userAttributes = buildUserAttributes(email, input);
50
+ const userAttributes = buildStandardAttributes(email, input);
51
+ const customAttributes = buildCustomAttributes(input);
43
52
  let userSub;
44
53
  try {
45
54
  const res = await client.send(new SignUpCommand({
@@ -60,6 +69,20 @@ export async function signUpUser(input, config = loadAuthServerConfig()) {
60
69
  throw mapProviderError(err, 'sign_up_failed');
61
70
  }
62
71
  if (!autoConfirm) {
72
+ // No confirm step to piggyback on — apply the custom attributes
73
+ // on their own. Admin calls work on unconfirmed users.
74
+ if (customAttributes.length > 0) {
75
+ try {
76
+ await client.send(new AdminUpdateUserAttributesCommand({
77
+ UserPoolId: config.userPoolId,
78
+ Username: email,
79
+ UserAttributes: customAttributes,
80
+ }));
81
+ }
82
+ catch (err) {
83
+ throw mapProviderError(err, 'sign_up_failed');
84
+ }
85
+ }
63
86
  return { userSub, confirmed: false };
64
87
  }
65
88
  // Confirm + mark email verified so the next sign-in succeeds
@@ -82,6 +105,7 @@ export async function signUpUser(input, config = loadAuthServerConfig()) {
82
105
  UserAttributes: [
83
106
  { Name: 'email', Value: email },
84
107
  { Name: 'email_verified', Value: 'true' },
108
+ ...customAttributes,
85
109
  ],
86
110
  }));
87
111
  }
@@ -90,7 +114,8 @@ export async function signUpUser(input, config = loadAuthServerConfig()) {
90
114
  }
91
115
  return { userSub, confirmed: true };
92
116
  }
93
- function buildUserAttributes(email, input) {
117
+ /** Standard attributes — the only ones the app client is allowed to write on `SignUp`. */
118
+ function buildStandardAttributes(email, input) {
94
119
  const out = [{ Name: 'email', Value: email }];
95
120
  if (input.name !== undefined)
96
121
  out.push({ Name: 'name', Value: input.name });
@@ -99,9 +124,13 @@ function buildUserAttributes(email, input) {
99
124
  continue; // already set above
100
125
  out.push({ Name: name, Value: value });
101
126
  }
102
- for (const [name, value] of Object.entries(input.customAttributes ?? {})) {
103
- out.push({ Name: `custom:${name}`, Value: value });
104
- }
105
127
  return out;
106
128
  }
129
+ /** `custom:*` attributes — applied through the admin API, never through the client. */
130
+ function buildCustomAttributes(input) {
131
+ return Object.entries(input.customAttributes ?? {}).map(([name, value]) => ({
132
+ Name: `custom:${name}`,
133
+ Value: value,
134
+ }));
135
+ }
107
136
  //# sourceMappingURL=sign-up.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sign-up.js","sourceRoot":"","sources":["../../src/server/sign-up.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EACL,yBAAyB,EACzB,gCAAgC,EAChC,aAAa,GAEd,MAAM,2CAA2C,CAAC;AAEnD,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAgD1D;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAC9B,KAAkB,EAClB,SAA2B,oBAAoB,EAAE;IAEjD,MAAM,MAAM,GAAG,gBAAgB,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;IAChE,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;IACxC,MAAM,WAAW,GAAG,KAAK,CAAC,WAAW,IAAI,IAAI,CAAC;IAE9C,MAAM,cAAc,GAAG,mBAAmB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAEzD,IAAI,OAAe,CAAC;I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AAI,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;AAwB5B;;;;;;GAMG;AACH,wBAAgB,mCAAmC,CACjD,CAAC,GAAE,OAAe,GACjB,qBAAqB,CAgEvB"}
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"}
@@ -23,14 +23,23 @@
23
23
  * write, `EXTRACT(EPOCH …) * 1000` on read.
24
24
  */
25
25
  import { query } from '@venturekit/data';
26
+ /** Mapper options pinning the raw `snake_case` row shape for this store's reads. */
27
+ const RAW_ROWS = { camelCase: false };
26
28
  function rowToRecord(r) {
29
+ const codeHash = r.code_hash ?? r.codeHash;
30
+ const expiresAt = r.expires_at ?? r.expiresAt;
31
+ const maxAttempts = r.max_attempts ?? r.maxAttempts;
32
+ if (codeHash === undefined || expiresAt === undefined || maxAttempts === undefined) {
33
+ throw new Error('[@venturekit/auth] vk_verification_codes row is missing code_hash / expires_at / ' +
34
+ 'max_attempts — the querier did not return the columns the store selected.');
35
+ }
27
36
  return {
28
37
  channel: r.channel,
29
38
  identifier: r.identifier,
30
- codeHash: r.code_hash,
31
- expiresAt: Number(r.expires_at),
39
+ codeHash,
40
+ expiresAt: Number(expiresAt),
32
41
  attempts: r.attempts,
33
- maxAttempts: r.max_attempts,
42
+ maxAttempts,
34
43
  };
35
44
  }
36
45
  /**
@@ -72,7 +81,7 @@ export function createPostgresVerificationCodeStore(q = query) {
72
81
  LIMIT 1`, [channel, identifier], (rows) => {
73
82
  const r = rows[0];
74
83
  return r ? rowToRecord(r) : undefined;
75
- });
84
+ }, RAW_ROWS);
76
85
  },
77
86
  async incrementAttempts({ channel, identifier }) {
78
87
  return q(`UPDATE vk_verification_codes
@@ -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;AAiBvD,SAAS,WAAW,CAAC,CAAsB;IACzC,OAAO;QACL,OAAO,EAAE,CAAC,CAAC,OAAO;QAClB,UAAU,EAAE,CAAC,CAAC,UAAU;QACxB,QAAQ,EAAE,CAAC,CAAC,SAAS;QACrB,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC,UAAU,CAAC;QAC/B,QAAQ,EAAE,CAAC,CAAC,QAAQ;QACpB,WAAW,EAAE,CAAC,CAAC,YAAY;KAC5B,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,mCAAmC,CACjD,IAAa,KAAK;IAElB,OAAO;QACL,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE;YACjE,+DAA+D;YAC/D,kEAAkE;YAClE,iDAAiD;YACjD,MAAM,CAAC,CACL,wEAAwE,CACzE,CAAC;YACF,iEAAiE;YACjE,iEAAiE;YACjE,+DAA+D;YAC/D,oCAAoC;YACpC,MAAM,CAAC,CACL;;;;;;;;qCAQ6B,EAC7B,CAAC,OAA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C,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;YACxC,CAAC,EACD,QAAQ,CACT,CAAC;QACJ,CAAC;QAED,KAAK,CAAC,iBAAiB,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE;YAC7C,OAAO,CAAC,CACN;;;6BAGqB,EACrB,CAAC,OAAO,EAAE,UAAU,CAAC,EACrB,CAAC,IAAI,EAAE,EAAE,CACN,IAAI,CAAC,CAAC,CAAsC,EAAE,QAAQ,IAAI,CAAC,CAC/D,CAAC;QACJ,CAAC;QAED,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE;YAClC,MAAM,CAAC,CACL,0EAA0E,EAC1E,CAAC,OAAO,EAAE,UAAU,CAAC,CACtB,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venturekit/auth",
3
- "version": "0.0.38",
3
+ "version": "0.0.39",
4
4
  "description": "Authentication and authorization for VentureKit",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -41,14 +41,14 @@
41
41
  }
42
42
  },
43
43
  "dependencies": {
44
- "@venturekit/core": "0.0.38",
44
+ "@venturekit/core": "0.0.39",
45
45
  "@aws-sdk/client-cognito-identity-provider": "^3.1126.0",
46
46
  "@aws-sdk/client-secrets-manager": "^3.1126.0",
47
47
  "aws-jwt-verify": "^4.0.1"
48
48
  },
49
49
  "peerDependencies": {
50
- "@venturekit/data": "0.0.38",
51
- "@venturekit/runtime": "0.0.38"
50
+ "@venturekit/data": "0.0.39",
51
+ "@venturekit/runtime": "0.0.39"
52
52
  },
53
53
  "peerDependenciesMeta": {
54
54
  "@venturekit/data": {
@@ -59,8 +59,8 @@
59
59
  }
60
60
  },
61
61
  "devDependencies": {
62
- "@venturekit/data": "0.0.38",
63
- "@venturekit/runtime": "0.0.38",
62
+ "@venturekit/data": "0.0.39",
63
+ "@venturekit/runtime": "0.0.39",
64
64
  "@types/aws-lambda": "^8.10.163",
65
65
  "@types/node": "^26.5.1",
66
66
  "typescript": "^5.3.0"
@@ -0,0 +1,38 @@
1
+ -- @venturekit/auth — customer API keys (inbound machine-to-machine auth).
2
+ --
3
+ -- A key is `vk_<prefix><secret>`; only the SHA-256 of the full token is
4
+ -- stored, so a database read-out yields nothing usable. `prefix` (the
5
+ -- first 12 characters, non-secret) is what admin screens display and what
6
+ -- `verifyApiKey` uses to narrow the lookup before the constant-time hash
7
+ -- compare.
8
+ --
9
+ -- `owner_id` is the Cognito sub the key ACTS AS (its scopes are the key's
10
+ -- own, never inherited); `tenant_id` scopes it to one tenant. Both are
11
+ -- nullable TEXT so single-tenant / service keys fit, and apps may add RLS
12
+ -- on top. `scopes` feed `handler({ scopes })` exactly like JWT scopes.
13
+
14
+ CREATE TABLE IF NOT EXISTS vk_api_keys (
15
+ id TEXT PRIMARY KEY,
16
+ prefix TEXT NOT NULL,
17
+ key_hash TEXT NOT NULL UNIQUE,
18
+ name TEXT NOT NULL,
19
+ owner_id TEXT,
20
+ tenant_id TEXT,
21
+ scopes TEXT[] NOT NULL DEFAULT '{}',
22
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
23
+ expires_at TIMESTAMPTZ,
24
+ last_used_at TIMESTAMPTZ,
25
+ revoked_at TIMESTAMPTZ,
26
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
27
+ );
28
+
29
+ CREATE INDEX IF NOT EXISTS vk_api_keys_owner_idx
30
+ ON vk_api_keys (owner_id)
31
+ WHERE revoked_at IS NULL;
32
+
33
+ CREATE INDEX IF NOT EXISTS vk_api_keys_tenant_idx
34
+ ON vk_api_keys (tenant_id)
35
+ WHERE revoked_at IS NULL;
36
+
37
+ COMMENT ON TABLE vk_api_keys IS
38
+ 'Customer / service API keys — hashed. Structure owned by @venturekit/auth; issued and verified through its api-keys helpers.';
@@ -0,0 +1,37 @@
1
+ -- @venturekit/auth — invitations.
2
+ --
3
+ -- A single-use, expiring token that lets an invited person create (or
4
+ -- attach) their account with the role / tenant the inviter chose. Only
5
+ -- the SHA-256 of the token is stored; the plaintext travels in the invite
6
+ -- e-mail link and nowhere else.
7
+ --
8
+ -- `tenant_id`, `role` and `metadata` are opaque to the framework: the app
9
+ -- reads them back from the accepted invitation (`acceptInvitation` returns
10
+ -- the row) to create its membership / profile rows in the same
11
+ -- transaction. `email` is lower-cased on write.
12
+
13
+ CREATE TABLE IF NOT EXISTS vk_invitations (
14
+ id TEXT PRIMARY KEY,
15
+ token_hash TEXT NOT NULL UNIQUE,
16
+ email TEXT NOT NULL,
17
+ tenant_id TEXT,
18
+ role TEXT,
19
+ invited_by TEXT,
20
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
21
+ expires_at TIMESTAMPTZ NOT NULL,
22
+ accepted_at TIMESTAMPTZ,
23
+ accepted_by TEXT,
24
+ revoked_at TIMESTAMPTZ,
25
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
26
+ );
27
+
28
+ -- "Is there an open invitation for this address (in this tenant)?"
29
+ CREATE INDEX IF NOT EXISTS vk_invitations_open_email_idx
30
+ ON vk_invitations (email, tenant_id)
31
+ WHERE accepted_at IS NULL AND revoked_at IS NULL;
32
+
33
+ CREATE INDEX IF NOT EXISTS vk_invitations_tenant_idx
34
+ ON vk_invitations (tenant_id, created_at DESC);
35
+
36
+ COMMENT ON TABLE vk_invitations IS
37
+ 'Single-use invitation tokens (hashed). Structure owned by @venturekit/auth; issued / accepted through its invitations helpers.';