@oxyhq/contracts 0.32.0 → 0.34.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.
@@ -7,6 +7,7 @@
7
7
  * {@link ACCOUNT_CATEGORY_IDS} for the four rules that govern it.
8
8
  */
9
9
  import { z } from 'zod';
10
+ import { usernameSchema } from './username.js';
10
11
  /**
11
12
  * The union is spelled out above and the array proves coverage BOTH ways
12
13
  * (`satisfies` here, the `Gap` alias below) — the same shape this package's
@@ -35,9 +36,13 @@ export const CHILD_ACCOUNT_KINDS = [
35
36
  ];
36
37
  export const childAccountKindSchema = z.enum(CHILD_ACCOUNT_KINDS);
37
38
  /**
38
- * Whether an operator may ACT AS an account of this kind switch the whole app
39
- * into it (`POST /accounts/:id/switch`) or authorise an app to act as it
40
- * (an OAuth delegated subject).
39
+ * Whether an account of this kind may be the SUBJECT OF A DELEGATION — an
40
+ * application acting as it on some person's authority. `POST /internal/accounts/
41
+ * :id/service-switch` and the OAuth delegated subject both gate on this.
42
+ *
43
+ * It is NOT the question an account switcher asks. See
44
+ * {@link isOperatorSwitchTargetKind}, and the note below on why the difference
45
+ * is `bot`.
41
46
  *
42
47
  * Two kinds are refused, for opposite reasons:
43
48
  *
@@ -54,9 +59,43 @@ export const childAccountKindSchema = z.enum(CHILD_ACCOUNT_KINDS);
54
59
  * Consumers must gate on this predicate rather than testing `kind === 'personal'`,
55
60
  * which silently admits every kind added after it was written.
56
61
  */
57
- export function isActAsEligibleKind(kind) {
62
+ export function isDelegatedActAsEligibleKind(kind) {
58
63
  return kind === 'organization' || kind === 'project' || kind === 'bot';
59
64
  }
65
+ /**
66
+ * Whether a PERSON may switch into an account of this kind — become it, in an
67
+ * account switcher, for the rest of their session.
68
+ *
69
+ * ## Why this is not the same question as {@link isDelegatedActAsEligibleKind}
70
+ *
71
+ * The two differ on exactly one kind, `bot`, and that difference is the whole
72
+ * reason both exist.
73
+ *
74
+ * **A bot is not something you become. It is something that operates on your
75
+ * behalf.** Its whole purpose is to act while nobody is present: an application
76
+ * holds a credential, names the human whose authority it borrows, and speaks as
77
+ * the bot. That is delegation, and it is what
78
+ * {@link isDelegatedActAsEligibleKind} admits it for.
79
+ *
80
+ * Handing a person the bot's seat instead inverts that. It puts a human inside
81
+ * the identity that exists to act without one, and it does so on the human's own
82
+ * device, next to their personal login — which is precisely what happened: a
83
+ * `bot` account held a live session on a person's device, offered to them by a
84
+ * switcher that had asked the delegation question by mistake.
85
+ *
86
+ * `channel` is refused here as well, for the reason set out above, and
87
+ * `personal` because assuming somebody else's login is impersonation.
88
+ *
89
+ * ## This is the narrower predicate, deliberately
90
+ *
91
+ * Everything a person may become, a service may also act as; the reverse does
92
+ * not hold. A caller that is unsure which question it is asking wants THIS one:
93
+ * being wrong here withholds an affordance, while being wrong the other way
94
+ * hands out a seat.
95
+ */
96
+ export function isOperatorSwitchTargetKind(kind) {
97
+ return kind === 'organization' || kind === 'project';
98
+ }
60
99
  /**
61
100
  * Narrow an unknown value to an {@link AccountKind}.
62
101
  *
@@ -287,7 +326,7 @@ export const accountCategoriesSchema = z
287
326
  *
288
327
  * A person has interests, not a sector — and their interests are not a
289
328
  * classification anybody else gets to read off their profile. Spelled out
290
- * positively, like {@link isActAsEligibleKind} and for the same reason: a `kind
329
+ * positively, like {@link isDelegatedActAsEligibleKind} and for the same reason: a `kind
291
330
  * !== 'personal'` test silently admits every kind invented after it was
292
331
  * written, whereas this list forces whoever adds one to decide.
293
332
  */
@@ -342,7 +381,14 @@ const accountNameSchema = z
342
381
  export const createAccountRequestSchema = z.object({
343
382
  parentAccountId: z.string().trim().min(1).optional(),
344
383
  kind: childAccountKindSchema,
345
- username: z.string().trim().min(1).max(100),
384
+ /**
385
+ * The SAME policy a person's handle is held to. `users.username` is one unique
386
+ * index, so a managed account may not reserve a name a person could not ask
387
+ * for — and this route's predecessor (`.min(1).max(100)` here, `^[\w.-]+$`
388
+ * with no ceiling in the service) is how a one-character or dotted or
389
+ * 100-character handle became reachable for bots alone.
390
+ */
391
+ username: usernameSchema,
346
392
  name: accountNameSchema,
347
393
  bio: z.string().trim().max(500).optional(),
348
394
  avatar: z.string().optional(),
package/dist/esm/index.js CHANGED
@@ -9,7 +9,8 @@
9
9
  * Platform-agnostic — zod is the only runtime dependency. No react/react-native/
10
10
  * expo, no `require()` in the ESM build.
11
11
  */
12
- export { ACCOUNT_KINDS, accountKindSchema, CHILD_ACCOUNT_KINDS, childAccountKindSchema, isAccountKind, isActAsEligibleKind, ACCOUNT_CATEGORY_IDS, ACCOUNT_CATEGORY_KINDS, accountCategoriesSchema, accountCategoryIdSchema, isSelectableAccountCategoryId, kindAcceptsAccountCategories, MAX_ACCOUNT_CATEGORIES, newlyAddedRetiredCategories, RETIRED_ACCOUNT_CATEGORY_IDS, SELECTABLE_ACCOUNT_CATEGORY_IDS, createAccountRequestSchema, } from './accountGraph.js';
12
+ export { ACCOUNT_KINDS, accountKindSchema, CHILD_ACCOUNT_KINDS, childAccountKindSchema, isAccountKind, isDelegatedActAsEligibleKind, isOperatorSwitchTargetKind, ACCOUNT_CATEGORY_IDS, ACCOUNT_CATEGORY_KINDS, accountCategoriesSchema, accountCategoryIdSchema, isSelectableAccountCategoryId, kindAcceptsAccountCategories, MAX_ACCOUNT_CATEGORIES, newlyAddedRetiredCategories, RETIRED_ACCOUNT_CATEGORY_IDS, SELECTABLE_ACCOUNT_CATEGORY_IDS, createAccountRequestSchema, } from './accountGraph.js';
13
+ export { usernameSchema, isValidUsername, stripDisallowedUsernameCharacters, USERNAME_MIN_LENGTH, USERNAME_MAX_LENGTH, USERNAME_INVALID_MESSAGE, } from './username.js';
13
14
  export {
14
15
  // Schemas
15
16
  userNameSchema, userRelationshipSchema, themePreferenceSchema, userResponseSchema, userProfileUpdateSchema, currentUserResponseSchema, deviceLinkedSessionSchema, deviceLinkedSessionsResponseSchema,
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Username policy — the ONE rule, for every kind of account.
3
+ *
4
+ * A username is a HANDLE: the routing key of a profile URL (`/@alice`), the
5
+ * local part of a webfinger `acct:`, and a login identifier. `users.username`
6
+ * carries a single unique index, `lower(btrim(username))`, and people, bots,
7
+ * organizations, projects and channels all draw from it. There is no per-kind
8
+ * namespace, so there is no per-kind rule — a bot that may reserve a name a
9
+ * person cannot ask for is a disagreement inside one index, not a variant.
10
+ *
11
+ * ## Why this file exists
12
+ *
13
+ * Seven rules governed this one namespace: four validators (this package's
14
+ * predecessor in `@oxyhq/api`, `@oxyhq/core`, `@oxyhq/commons`, and one written
15
+ * inline in `AccountService.resolveUniqueUsername`) and three that COERCED —
16
+ * silently deleting the characters they disliked, which hands somebody an
17
+ * account under a name they never chose. They lived in five packages and no test
18
+ * asserted they agreed. `contracts` is where the single declaration can actually
19
+ * live: `api`, `core`, `commons`, `services` and `auth` all already depend on it,
20
+ * so every write path can IMPORT the rule instead of restating it.
21
+ * `__tests__/usernamePolicySingleSource.test.ts` fails if a second one appears.
22
+ *
23
+ * ## The rule, and why each part of it
24
+ *
25
+ * ```
26
+ * 3–30 characters
27
+ * first and last character: [A-Za-z0-9]
28
+ * interior: [A-Za-z0-9_-]
29
+ * never two separators in a row
30
+ * ```
31
+ *
32
+ * - **Hyphens are admitted because the DATABASE already admits them.**
33
+ * `internal_cost_centers_slug_check` is a CHECK constraint —
34
+ * `^[a-z0-9][a-z0-9-]{0,62}$` — and `seed-internal-cost-centers` mints a
35
+ * `project` account whose username IS the slug; four of the five declared
36
+ * centres contain a hyphen. An alphanumeric-only handle rule would contradict
37
+ * a constraint written to permit them, and would make those centres
38
+ * unmintable. This is the argument, not the four hyphenated accounts that
39
+ * happen to exist — they are a symptom.
40
+ * - **Dots are NOT admitted.** A dot is the delimiter that separates handle from
41
+ * domain in the federated form this same column stores for remote actors
42
+ * (`alice@mastodon.social`), it collides with extension-style routing
43
+ * (`/@alice.json`), and `n.ate` beside `nate` is the strongest confusable pair
44
+ * an ASCII handle can produce. Only the inline account rule ever accepted one,
45
+ * and it accepted it by accident: its `[\w.-]` was written for a SLUG.
46
+ * - **A length bound, always.** The account path had none — the only ceiling was
47
+ * a `.max(100)` on the wire schema. 3 is the floor because `oxy`, the platform
48
+ * owner's own organization, is three characters. 30 is the ceiling four of the
49
+ * seven rules and the availability endpoint already published.
50
+ * - **First and last character alphanumeric, and no `--` / `__` / `-_` run.**
51
+ * Both are free — no account uses such a name — and they remove the
52
+ * confusable shapes that admitting two separators would otherwise introduce.
53
+ *
54
+ * ## Case, and what this schema deliberately does not do
55
+ *
56
+ * **Case is PRESERVED.** Uniqueness is decided by the database's
57
+ * `lower(btrim(username))` index, so `Alice` and `alice` cannot coexist, but a
58
+ * name that was typed with a capital keeps it. This schema therefore never
59
+ * lower-cases: rewriting a caller's input is how `resolveUniqueUsername` used to
60
+ * return `mybot` to somebody who asked for `MyBot`.
61
+ *
62
+ * **This is a WRITE-path rule.** It states what may be newly stored, not what may
63
+ * be read. Rows that predate it — including 11 with no username at all — must go
64
+ * on loading, resolving and rendering; validating on a read turns an existing
65
+ * account into a 500.
66
+ *
67
+ * **It does not govern remote actors.** The same column holds ~73k federated
68
+ * rows in `handle@domain` form, written by `POST /users/resolve` through its own
69
+ * normalizer. Those are another server's namespace; this rule would reject every
70
+ * one of them and must never be pointed at that path.
71
+ *
72
+ * ## Usable by a handle GENERATOR, deliberately
73
+ *
74
+ * Slug generators are how the eighth copy of this rule appears. Alia's
75
+ * `suggestAgentUsername` builds one from an agent's name and re-derives a subset
76
+ * of these rules by hand — its own docblock admits it ("A leading digit or an
77
+ * empty slug both fail Oxy's username rules") — and, having no minimum, proposes
78
+ * `al` for an agent called "Al", which the server then refuses.
79
+ *
80
+ * So this module answers a generator's three questions without dragging a server
81
+ * dependency along. It is zod and nothing else, so it imports cleanly into a
82
+ * React Native bundle or another repo's backend:
83
+ *
84
+ * - *Does this candidate pass?* {@link isValidUsername}, or `safeParse` when the
85
+ * reason matters.
86
+ * - *How short is too short, how long is too long?* {@link USERNAME_MIN_LENGTH}
87
+ * and {@link USERNAME_MAX_LENGTH}, so a generator can pad or truncate instead
88
+ * of guessing and being 400ed.
89
+ * - *Which characters survive?* {@link stripDisallowedUsernameCharacters}.
90
+ *
91
+ * A generator PROPOSES; only `POST /accounts` decides, and a taken handle comes
92
+ * back as a 409 for the client to retry with a fresh suggestion. Nothing here
93
+ * knows what is taken, and it must not pretend to.
94
+ */
95
+ import { z } from 'zod';
96
+ /** Shortest storable handle. `oxy` sets the floor. */
97
+ export const USERNAME_MIN_LENGTH = 3;
98
+ /** Longest storable handle, and the `maxLength` an input field should carry. */
99
+ export const USERNAME_MAX_LENGTH = 30;
100
+ /** The 400 / inline-validation copy for every path that rejects a handle. */
101
+ export const USERNAME_INVALID_MESSAGE = 'Username must be 3-30 characters, use only letters, numbers, hyphens and underscores, ' +
102
+ 'start and end with a letter or number, and never repeat a separator';
103
+ /**
104
+ * Alphanumeric runs joined by single separators, as a SOURCE string.
105
+ *
106
+ * A string rather than a literal because the OpenAPI docblocks that publish this
107
+ * rule (`POST /auth/register`, `PUT /users/:userId`) must quote it verbatim, and
108
+ * `usernamePolicySingleSource.test.ts` compares them against THIS constant. A
109
+ * published `pattern:` that drifts from the enforced rule is a lie told to every
110
+ * client that generates from the spec, and it is exactly the kind of copy nobody
111
+ * notices going stale.
112
+ *
113
+ * Deliberately NOT re-exported from the package barrel: it exists for the
114
+ * schema below and for that one gate. Anything validating a username uses
115
+ * {@link usernameSchema}, so there is no second way to ask the question.
116
+ *
117
+ * Written as an unambiguous alternation rather than a lookahead: every character
118
+ * belongs to exactly one branch, so matching is linear and there is no
119
+ * backtracking to bound. It also carries no `\p{…}` property escape, which
120
+ * mobile Hermes throws on at runtime — this module is reachable from every React
121
+ * Native consumer.
122
+ */
123
+ export const USERNAME_PATTERN_SOURCE = '^[A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*$';
124
+ const USERNAME_PATTERN = new RegExp(USERNAME_PATTERN_SOURCE);
125
+ /**
126
+ * The one username policy, as a schema.
127
+ *
128
+ * `.trim()` first, so surrounding whitespace is a typo rather than a rejection —
129
+ * but interior whitespace is NOT removed. It falls to the pattern, because
130
+ * squashing `"al ice"` into `"alice"` would hand the user an account under a name
131
+ * they never chose. Every write path validates through THIS object; nothing
132
+ * re-implements it.
133
+ */
134
+ export const usernameSchema = z
135
+ .string()
136
+ .trim()
137
+ .min(USERNAME_MIN_LENGTH, USERNAME_INVALID_MESSAGE)
138
+ .max(USERNAME_MAX_LENGTH, USERNAME_INVALID_MESSAGE)
139
+ .regex(USERNAME_PATTERN, USERNAME_INVALID_MESSAGE);
140
+ /**
141
+ * Whether a candidate handle is storable — the boolean form, for input surfaces
142
+ * that show a message as somebody types rather than throwing.
143
+ *
144
+ * Answers from {@link usernameSchema}, so a client's inline check and the
145
+ * server's 400 cannot disagree.
146
+ */
147
+ export function isValidUsername(candidate) {
148
+ return usernameSchema.safeParse(candidate).success;
149
+ }
150
+ /**
151
+ * Drop the characters the policy forbids, for an input field that filters
152
+ * keystrokes.
153
+ *
154
+ * This is a TYPING aid and nothing else — the result still has to pass
155
+ * {@link usernameSchema}, which is what decides. It does not lower-case (case is
156
+ * preserved, see the header) and it cannot repair a name: a value that is too
157
+ * short, edge-separated or doubly-separated comes back unchanged and fails
158
+ * validation with a message, which is the outcome the coercing rules this
159
+ * replaces used to hide.
160
+ */
161
+ export function stripDisallowedUsernameCharacters(input) {
162
+ return input.replace(/[^A-Za-z0-9_-]/g, '');
163
+ }