@smartcrab/contracts-public 0.1.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 (54) hide show
  1. package/LICENSE +202 -0
  2. package/dist/association-files.d.ts +46 -0
  3. package/dist/association-files.js +32 -0
  4. package/dist/config.d.ts +57 -0
  5. package/dist/config.js +38 -0
  6. package/dist/email.d.ts +55 -0
  7. package/dist/email.js +39 -0
  8. package/dist/index.d.ts +23 -0
  9. package/dist/index.js +23 -0
  10. package/dist/me.d.ts +297 -0
  11. package/dist/me.js +140 -0
  12. package/dist/oidc.d.ts +239 -0
  13. package/dist/oidc.js +230 -0
  14. package/dist/outcome.d.ts +19 -0
  15. package/dist/outcome.js +2 -0
  16. package/dist/passkeys.d.ts +257 -0
  17. package/dist/passkeys.js +162 -0
  18. package/dist/primitives.d.ts +60 -0
  19. package/dist/primitives.js +52 -0
  20. package/dist/redirect-uri.d.ts +25 -0
  21. package/dist/redirect-uri.js +39 -0
  22. package/dist/scopes.d.ts +30 -0
  23. package/dist/scopes.js +46 -0
  24. package/dist/social.d.ts +44 -0
  25. package/dist/social.js +35 -0
  26. package/dist/transaction-status.d.ts +53 -0
  27. package/dist/transaction-status.js +37 -0
  28. package/dist/transactions.d.ts +144 -0
  29. package/dist/transactions.js +103 -0
  30. package/package.json +43 -0
  31. package/src/association-files.test.ts +71 -0
  32. package/src/association-files.ts +46 -0
  33. package/src/config.test.ts +66 -0
  34. package/src/config.ts +62 -0
  35. package/src/email.test.ts +40 -0
  36. package/src/email.ts +50 -0
  37. package/src/index.ts +23 -0
  38. package/src/me.test.ts +116 -0
  39. package/src/me.ts +223 -0
  40. package/src/oidc.test.ts +224 -0
  41. package/src/oidc.ts +296 -0
  42. package/src/outcome.ts +17 -0
  43. package/src/passkeys.test.ts +80 -0
  44. package/src/passkeys.ts +218 -0
  45. package/src/primitives.ts +79 -0
  46. package/src/redirect-uri.test.ts +118 -0
  47. package/src/redirect-uri.ts +86 -0
  48. package/src/scopes.test.ts +51 -0
  49. package/src/scopes.ts +63 -0
  50. package/src/social.test.ts +34 -0
  51. package/src/social.ts +43 -0
  52. package/src/transaction-status.ts +44 -0
  53. package/src/transactions.test.ts +153 -0
  54. package/src/transactions.ts +129 -0
package/src/me.ts ADDED
@@ -0,0 +1,223 @@
1
+ import { z } from "zod";
2
+ import { emailChallengeResponseSchema } from "./email.js";
3
+ import {
4
+ passkeyRegistrationOptionsRequestSchema,
5
+ passkeyRegistrationOptionsResponseSchema,
6
+ passkeyRegistrationVerifyRequestSchema,
7
+ passkeySummarySchema,
8
+ } from "./passkeys.js";
9
+ import {
10
+ clientIdSchema,
11
+ emailOtpCodeSchema,
12
+ identityIdSchema,
13
+ isoDateTimeSchema,
14
+ passkeyIdSchema,
15
+ redirectUriSchema,
16
+ sessionIdSchema,
17
+ userIdSchema,
18
+ } from "./primitives.js";
19
+ import { socialProviderSchema, socialStartResponseSchema } from "./social.js";
20
+
21
+ /**
22
+ * The authenticated self-service surface (design.md §16.2 route list). All
23
+ * responses here project persisted rows (design.md §12.1-§12.5) minus
24
+ * internal/sensitive columns (`security_version`, `metadata_json`,
25
+ * `credential_id`, `public_key`, `sign_count`, token ciphertexts, hashes).
26
+ */
27
+
28
+ // ---------------------------------------------------------------------------
29
+ // GET/PATCH /v1/me (design.md §12.1 `users`)
30
+ // ---------------------------------------------------------------------------
31
+
32
+ export const USER_STATUSES = ["active", "blocked", "pending_deletion"] as const;
33
+ export const userStatusSchema = z.enum(USER_STATUSES);
34
+ export type UserStatus = (typeof USER_STATUSES)[number];
35
+
36
+ export const meUserSchema = z.strictObject({
37
+ user_id: userIdSchema,
38
+ email: z.email().nullable(),
39
+ email_verified: z.boolean(),
40
+ name: z.string().nullable(),
41
+ avatar_url: z.url().nullable(),
42
+ locale: z.string().nullable(),
43
+ timezone: z.string().nullable(),
44
+ status: userStatusSchema,
45
+ created_at: isoDateTimeSchema,
46
+ last_login_at: isoDateTimeSchema.nullable(),
47
+ });
48
+ export type MeUser = z.infer<typeof meUserSchema>;
49
+
50
+ /**
51
+ * Email is intentionally excluded: changing it goes through
52
+ * `POST /v1/me/email/change/start` (dual old/new-email verification,
53
+ * design.md §25), never a direct `PATCH`.
54
+ */
55
+ export const meUpdateRequestSchema = z.strictObject({
56
+ name: z.string().min(1).max(200).optional(),
57
+ avatar_url: z.url().optional(),
58
+ locale: z.string().min(1).max(35).optional(),
59
+ timezone: z.string().min(1).max(64).optional(),
60
+ });
61
+ export type MeUpdateRequest = z.infer<typeof meUpdateRequestSchema>;
62
+
63
+ /** `PATCH /v1/me` returns the updated profile, same shape as `GET /v1/me`. */
64
+ export const meUpdateResponseSchema = meUserSchema;
65
+ export type MeUpdateResponse = z.infer<typeof meUpdateResponseSchema>;
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // /v1/me/passkeys (design.md §17.1)
69
+ // ---------------------------------------------------------------------------
70
+
71
+ export const mePasskeysListResponseSchema = z.strictObject({
72
+ passkeys: z.array(passkeySummarySchema),
73
+ });
74
+ export type MePasskeysListResponse = z.infer<typeof mePasskeysListResponseSchema>;
75
+
76
+ /** Registration options depend on the session's user; only the RP ID may be named (design.md §8.3). */
77
+ export const mePasskeyRegistrationOptionsRequestSchema = passkeyRegistrationOptionsRequestSchema;
78
+ export type MePasskeyRegistrationOptionsRequest = z.infer<
79
+ typeof mePasskeyRegistrationOptionsRequestSchema
80
+ >;
81
+
82
+ /** Same fixed WebAuthn configuration as the transaction-scoped registration options (design.md §17.1). */
83
+ export const mePasskeyRegistrationOptionsResponseSchema = passkeyRegistrationOptionsResponseSchema;
84
+ export type MePasskeyRegistrationOptionsResponse = z.infer<
85
+ typeof mePasskeyRegistrationOptionsResponseSchema
86
+ >;
87
+
88
+ /** Same shape as the transaction-scoped credential + optional label (design.md §17.1). */
89
+ export const mePasskeyRegistrationVerifyRequestSchema = passkeyRegistrationVerifyRequestSchema;
90
+ export type MePasskeyRegistrationVerifyRequest = z.infer<
91
+ typeof mePasskeyRegistrationVerifyRequestSchema
92
+ >;
93
+
94
+ export const mePasskeyRegistrationVerifyResponseSchema = z.strictObject({
95
+ passkey: passkeySummarySchema,
96
+ });
97
+ export type MePasskeyRegistrationVerifyResponse = z.infer<
98
+ typeof mePasskeyRegistrationVerifyResponseSchema
99
+ >;
100
+
101
+ export const mePasskeyDeleteResponseSchema = z.strictObject({
102
+ passkey_id: passkeyIdSchema,
103
+ deleted: z.literal(true),
104
+ });
105
+ export type MePasskeyDeleteResponse = z.infer<typeof mePasskeyDeleteResponseSchema>;
106
+
107
+ // ---------------------------------------------------------------------------
108
+ // /v1/me/identities (design.md §20.5 `identities` table)
109
+ // ---------------------------------------------------------------------------
110
+
111
+ export const meIdentitySummarySchema = z.strictObject({
112
+ identity_id: identityIdSchema,
113
+ provider: socialProviderSchema,
114
+ linked_at: isoDateTimeSchema,
115
+ last_used_at: isoDateTimeSchema.nullable(),
116
+ });
117
+ export type MeIdentitySummary = z.infer<typeof meIdentitySummarySchema>;
118
+
119
+ export const meIdentitiesListResponseSchema = z.strictObject({
120
+ identities: z.array(meIdentitySummarySchema),
121
+ });
122
+ export type MeIdentitiesListResponse = z.infer<typeof meIdentitiesListResponseSchema>;
123
+
124
+ /**
125
+ * `redirect_uri` is where the authenticated app wants the user returned to
126
+ * after the linking OAuth round-trip completes (this is an app-context
127
+ * link, not a public auth transaction, so it carries its own return
128
+ * target rather than one fixed at transaction-create time).
129
+ */
130
+ export const meIdentityLinkRequestSchema = z.strictObject({
131
+ redirect_uri: redirectUriSchema,
132
+ });
133
+ export type MeIdentityLinkRequest = z.infer<typeof meIdentityLinkRequestSchema>;
134
+
135
+ /** Same shape as the transaction-scoped social start: a URL to open in the system browser. */
136
+ export const meIdentityLinkResponseSchema = socialStartResponseSchema;
137
+ export type MeIdentityLinkResponse = z.infer<typeof meIdentityLinkResponseSchema>;
138
+
139
+ export const meIdentityUnlinkResponseSchema = z.strictObject({
140
+ identity_id: identityIdSchema,
141
+ unlinked: z.literal(true),
142
+ });
143
+ export type MeIdentityUnlinkResponse = z.infer<typeof meIdentityUnlinkResponseSchema>;
144
+
145
+ // ---------------------------------------------------------------------------
146
+ // /v1/me/sessions (design.md §12.4 `sessions`, §24)
147
+ // ---------------------------------------------------------------------------
148
+
149
+ export const meSessionSummarySchema = z.strictObject({
150
+ session_id: sessionIdSchema,
151
+ client_id: clientIdSchema,
152
+ device_name: z.string().nullable(),
153
+ created_at: isoDateTimeSchema,
154
+ last_active_at: isoDateTimeSchema,
155
+ /** Whether this is the session the current request was authenticated with. */
156
+ current: z.boolean(),
157
+ });
158
+ export type MeSessionSummary = z.infer<typeof meSessionSummarySchema>;
159
+
160
+ export const meSessionsListResponseSchema = z.strictObject({
161
+ sessions: z.array(meSessionSummarySchema),
162
+ });
163
+ export type MeSessionsListResponse = z.infer<typeof meSessionsListResponseSchema>;
164
+
165
+ export const meSessionRevokeResponseSchema = z.strictObject({
166
+ session_id: sessionIdSchema,
167
+ revoked: z.literal(true),
168
+ });
169
+ export type MeSessionRevokeResponse = z.infer<typeof meSessionRevokeResponseSchema>;
170
+
171
+ /** design.md §24.3: revoking all sessions bumps `UserSecurityDO.securityVersion`. */
172
+ export const meSessionsRevokeAllResponseSchema = z.strictObject({
173
+ revoked: z.literal(true),
174
+ });
175
+ export type MeSessionsRevokeAllResponse = z.infer<typeof meSessionsRevokeAllResponseSchema>;
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // /v1/me/email/change/* (design.md §25: both old and new email must verify)
179
+ // ---------------------------------------------------------------------------
180
+
181
+ export const meEmailChangeStartRequestSchema = z.strictObject({
182
+ new_email: z.email(),
183
+ });
184
+ export type MeEmailChangeStartRequest = z.infer<typeof meEmailChangeStartRequestSchema>;
185
+
186
+ /** An OTP challenge sent to the CURRENT (old) email, confirming account ownership. */
187
+ export const meEmailChangeStartResponseSchema = emailChallengeResponseSchema;
188
+ export type MeEmailChangeStartResponse = z.infer<typeof meEmailChangeStartResponseSchema>;
189
+
190
+ export const meEmailChangeVerifyOldRequestSchema = z.strictObject({
191
+ challenge_id: z.string().min(1),
192
+ code: emailOtpCodeSchema,
193
+ });
194
+ export type MeEmailChangeVerifyOldRequest = z.infer<typeof meEmailChangeVerifyOldRequestSchema>;
195
+
196
+ /** A new OTP challenge, now sent to the NEW email. */
197
+ export const meEmailChangeVerifyOldResponseSchema = emailChallengeResponseSchema;
198
+ export type MeEmailChangeVerifyOldResponse = z.infer<typeof meEmailChangeVerifyOldResponseSchema>;
199
+
200
+ export const meEmailChangeVerifyNewRequestSchema = z.strictObject({
201
+ challenge_id: z.string().min(1),
202
+ code: emailOtpCodeSchema,
203
+ });
204
+ export type MeEmailChangeVerifyNewRequest = z.infer<typeof meEmailChangeVerifyNewRequestSchema>;
205
+
206
+ export const meEmailChangeVerifyNewResponseSchema = z.strictObject({
207
+ email: z.email(),
208
+ email_verified: z.literal(true),
209
+ });
210
+ export type MeEmailChangeVerifyNewResponse = z.infer<typeof meEmailChangeVerifyNewResponseSchema>;
211
+
212
+ // ---------------------------------------------------------------------------
213
+ // DELETE /v1/me (design.md §33: logical delete first; fresh session required, §24.4)
214
+ // ---------------------------------------------------------------------------
215
+
216
+ export const meDeleteRequestSchema = z.strictObject({});
217
+ export type MeDeleteRequest = z.infer<typeof meDeleteRequestSchema>;
218
+
219
+ export const meDeleteResponseSchema = z.strictObject({
220
+ user_id: userIdSchema,
221
+ status: z.literal("pending_deletion"),
222
+ });
223
+ export type MeDeleteResponse = z.infer<typeof meDeleteResponseSchema>;
@@ -0,0 +1,224 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import {
3
+ TOKEN_TTL_SECONDS,
4
+ authorizationCodeGrantRequestSchema,
5
+ authorizeRequestQuerySchema,
6
+ introspectionResponseSchema,
7
+ jwksDocumentSchema,
8
+ oauthErrorResponseSchema,
9
+ oidcDiscoveryDocumentSchema,
10
+ refreshTokenGrantRequestSchema,
11
+ revocationResponseSchema,
12
+ tokenRequestSchema,
13
+ tokenResponseSchema,
14
+ } from "./oidc.js";
15
+
16
+ describe("TOKEN_TTL_SECONDS (design.md §15.5)", () => {
17
+ test("matches every TTL in the design table", () => {
18
+ expect(TOKEN_TTL_SECONDS).toEqual({
19
+ authorizationCode: 60,
20
+ accessToken: 300,
21
+ idToken: 300,
22
+ refreshIdle: 30 * 24 * 60 * 60,
23
+ refreshAbsolute: 90 * 24 * 60 * 60,
24
+ loginSessionIdle: 7 * 24 * 60 * 60,
25
+ loginSessionAbsolute: 30 * 24 * 60 * 60,
26
+ });
27
+ });
28
+ });
29
+
30
+ const CODE_VERIFIER = "a".repeat(43);
31
+ const AUTH_CODE = `ac_${"a".repeat(32)}`;
32
+
33
+ describe("tokenRequestSchema — grant_type discrimination", () => {
34
+ test("accepts a valid authorization_code grant", () => {
35
+ const parsed = tokenRequestSchema.safeParse({
36
+ grant_type: "authorization_code",
37
+ code: AUTH_CODE,
38
+ redirect_uri: "com.customer.app:/oauth/callback",
39
+ code_verifier: CODE_VERIFIER,
40
+ client_id: `cli_${"a".repeat(32)}`,
41
+ });
42
+ expect(parsed.success).toBe(true);
43
+ if (parsed.success) {
44
+ expect(parsed.data.grant_type).toBe("authorization_code");
45
+ }
46
+ });
47
+
48
+ test("accepts a valid refresh_token grant", () => {
49
+ const parsed = tokenRequestSchema.safeParse({
50
+ grant_type: "refresh_token",
51
+ refresh_token: "some-opaque-refresh-token",
52
+ });
53
+ expect(parsed.success).toBe(true);
54
+ if (parsed.success) {
55
+ expect(parsed.data.grant_type).toBe("refresh_token");
56
+ }
57
+ });
58
+
59
+ test("rejects a grant_type/field mismatch (refresh_token body under authorization_code discriminant)", () => {
60
+ const parsed = tokenRequestSchema.safeParse({
61
+ grant_type: "authorization_code",
62
+ refresh_token: "some-opaque-refresh-token",
63
+ });
64
+ expect(parsed.success).toBe(false);
65
+ });
66
+
67
+ test("rejects an unsupported grant_type", () => {
68
+ const parsed = tokenRequestSchema.safeParse({
69
+ grant_type: "password",
70
+ username: "user",
71
+ password: "hunter2",
72
+ });
73
+ expect(parsed.success).toBe(false);
74
+ });
75
+
76
+ test("authorization_code grant requires code_verifier (PKCE mandatory, design.md §15.2/§15.4)", () => {
77
+ const parsed = authorizationCodeGrantRequestSchema.safeParse({
78
+ grant_type: "authorization_code",
79
+ code: AUTH_CODE,
80
+ redirect_uri: "com.customer.app:/oauth/callback",
81
+ });
82
+ expect(parsed.success).toBe(false);
83
+ });
84
+
85
+ test("refresh_token grant only narrows scope, schema itself allows an omitted scope", () => {
86
+ const parsed = refreshTokenGrantRequestSchema.safeParse({
87
+ grant_type: "refresh_token",
88
+ refresh_token: "some-opaque-refresh-token",
89
+ scope: "openid profile",
90
+ });
91
+ expect(parsed.success).toBe(true);
92
+ });
93
+ });
94
+
95
+ describe("authorizeRequestQuerySchema (design.md §15.1, §15.9)", () => {
96
+ const validQuery = {
97
+ response_type: "code",
98
+ client_id: `cli_${"a".repeat(32)}`,
99
+ redirect_uri: "https://app.customer.example/callback",
100
+ scope: "openid profile",
101
+ state: "abc123",
102
+ code_challenge: "a".repeat(43),
103
+ code_challenge_method: "S256",
104
+ };
105
+
106
+ test("accepts a valid authorize request", () => {
107
+ expect(authorizeRequestQuerySchema.safeParse(validQuery).success).toBe(true);
108
+ });
109
+
110
+ test("rejects response_type values other than 'code' (design.md §15.3: no Implicit Flow)", () => {
111
+ expect(
112
+ authorizeRequestQuerySchema.safeParse({ ...validQuery, response_type: "token" }).success,
113
+ ).toBe(false);
114
+ });
115
+
116
+ test("rejects code_challenge_method 'plain' (design.md §15.3)", () => {
117
+ expect(
118
+ authorizeRequestQuerySchema.safeParse({ ...validQuery, code_challenge_method: "plain" })
119
+ .success,
120
+ ).toBe(false);
121
+ });
122
+ });
123
+
124
+ describe("strict schemas reject unknown keys", () => {
125
+ test("tokenResponseSchema", () => {
126
+ const parsed = tokenResponseSchema.safeParse({
127
+ access_token: "at",
128
+ token_type: "Bearer",
129
+ expires_in: 300,
130
+ scope: "openid",
131
+ unexpected: true,
132
+ });
133
+ expect(parsed.success).toBe(false);
134
+ });
135
+
136
+ test("oauthErrorResponseSchema", () => {
137
+ const parsed = oauthErrorResponseSchema.safeParse({
138
+ error: "invalid_grant",
139
+ extra_field: "nope",
140
+ });
141
+ expect(parsed.success).toBe(false);
142
+ });
143
+
144
+ test("oauthErrorResponseSchema accepts every design-listed error code", () => {
145
+ const codes = [
146
+ "invalid_request",
147
+ "invalid_client",
148
+ "invalid_grant",
149
+ "unsupported_grant_type",
150
+ "invalid_scope",
151
+ "access_denied",
152
+ "server_error",
153
+ "temporarily_unavailable",
154
+ ];
155
+ for (const error of codes) {
156
+ expect(oauthErrorResponseSchema.safeParse({ error }).success).toBe(true);
157
+ }
158
+ expect(oauthErrorResponseSchema.safeParse({ error: "unauthorized_client" }).success).toBe(
159
+ false,
160
+ );
161
+ });
162
+
163
+ test("jwksDocumentSchema", () => {
164
+ const parsed = jwksDocumentSchema.safeParse({
165
+ keys: [
166
+ {
167
+ kty: "EC",
168
+ crv: "P-256",
169
+ x: "x",
170
+ y: "y",
171
+ kid: "key_1",
172
+ alg: "ES256",
173
+ use: "sig",
174
+ extra: 1,
175
+ },
176
+ ],
177
+ });
178
+ expect(parsed.success).toBe(false);
179
+ });
180
+
181
+ test("oidcDiscoveryDocumentSchema rejects an unsigned alg other than ES256", () => {
182
+ const parsed = oidcDiscoveryDocumentSchema.safeParse({
183
+ issuer: "https://id.example-auth.com/e/env_x",
184
+ authorization_endpoint: "https://id.example-auth.com/e/env_x/oauth2/authorize",
185
+ token_endpoint: "https://id.example-auth.com/e/env_x/oauth2/token",
186
+ userinfo_endpoint: "https://id.example-auth.com/e/env_x/oauth2/userinfo",
187
+ jwks_uri: "https://id.example-auth.com/e/env_x/oauth2/jwks",
188
+ revocation_endpoint: "https://id.example-auth.com/e/env_x/oauth2/revoke",
189
+ introspection_endpoint: "https://id.example-auth.com/e/env_x/oauth2/introspect",
190
+ end_session_endpoint: "https://id.example-auth.com/e/env_x/oauth2/logout",
191
+ response_types_supported: ["code"],
192
+ grant_types_supported: ["authorization_code", "refresh_token"],
193
+ code_challenge_methods_supported: ["S256"],
194
+ token_endpoint_auth_methods_supported: ["none"],
195
+ scopes_supported: ["openid", "profile", "email", "offline_access"],
196
+ subject_types_supported: ["public"],
197
+ id_token_signing_alg_values_supported: ["RS256"],
198
+ claims_supported: ["sub"],
199
+ });
200
+ expect(parsed.success).toBe(false);
201
+ });
202
+
203
+ test("introspectionResponseSchema rejects extra fields on the inactive shape", () => {
204
+ const parsed = introspectionResponseSchema.safeParse({ active: false, sub: "usr_x" });
205
+ expect(parsed.success).toBe(false);
206
+ });
207
+
208
+ test("introspectionResponseSchema accepts the minimal inactive shape and a populated active shape", () => {
209
+ expect(introspectionResponseSchema.safeParse({ active: false }).success).toBe(true);
210
+ expect(
211
+ introspectionResponseSchema.safeParse({
212
+ active: true,
213
+ scope: "openid profile",
214
+ client_id: `cli_${"a".repeat(32)}`,
215
+ sub: `usr_${"a".repeat(32)}`,
216
+ }).success,
217
+ ).toBe(true);
218
+ });
219
+
220
+ test("revocationResponseSchema is always an empty object", () => {
221
+ expect(revocationResponseSchema.safeParse({}).success).toBe(true);
222
+ expect(revocationResponseSchema.safeParse({ revoked: true }).success).toBe(false);
223
+ });
224
+ });