M1 security: close the password backdoor, apply re-review, pin E.164
Acts on an adversarial review of the M1 auth and authorization code. Five findings fixed; the rest recorded in SECURITY-FINDINGS.md as the M1 exit criteria rather than left in a tool transcript. - auth: serve /phone-number/request-password-reset, /phone-number/ reset-password and /sign-in/phone-number as 404. better-auth's phoneNumber() registers all three unconditionally -- they are NOT gated on emailAndPassword.enabled:false. Left live they form a silent second credential path: request-password-reset stores an OTP and sends no SMS (sendPasswordResetOTP was never configured, so the owner is never told), reset-password mints a bcrypt credential row, and sign-in/phone-number then accepts it forever with no OTP. The OTP gate still applies, so this is not remote unauthenticated takeover -- it converts one momentary OTP compromise into permanent access the victim cannot see or rotate. - auth: drop bearer(). It accepts the plaintext sessions.token column as an Authorization credential, making any single leaked row a replayable login. The mobile client it was added for is hypothetical. - auth: pin E.164 via phoneNumberValidator, and add toE164/isE164 to @linkder/shared. phone is UNIQUE and bans are per-account, so "+34600111222" and "0034600111222" being separately storable meant one handset could hold two accounts and a ban was escapable by retyping. 15 tests. - auth: NEXT_PUBLIC_APP_URL now throws in production instead of falling back to localhost, which was silently dropping Secure and the __Secure- prefix from the production session cookie. - pro.upsertProfile: actually apply requiresReReview. It was computed, returned to the client and never acted on, so a verified plumber could become a verified electrician in another city by ignoring a response flag. Now demotes to pending in the same transaction and audits it. Trade changes count as material (they did not before) -- the licence is per-trade. Needed a verified -> pending edge in VERIFICATION_GRAPH, which did not exist. Removed two untracked scratch repro files. The impersonation repro depended on bearer() for transport and no longer applies as written; the underlying finding (resolveSession drops impersonatedBy, so admin actions are audited as the victim) is open and documented. typecheck, lint, build clean; 127 tests pass. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -67,11 +67,44 @@ export const proRouter = router({
|
||||
|
||||
// Editing a live profile sends it back for review — a verified plumber must
|
||||
// not be able to quietly become an unverified electrician.
|
||||
const materiallyChanged =
|
||||
//
|
||||
// The trade list is part of "material": it is the single most important
|
||||
// thing verification actually checks (the licence is per-trade), so a
|
||||
// change of trade matters more than a change of radius.
|
||||
const previousCategoryIds = existing
|
||||
? (
|
||||
await ctx.db
|
||||
.select({ categoryId: schema.proCategories.categoryId })
|
||||
.from(schema.proCategories)
|
||||
.where(eq(schema.proCategories.proId, ctx.session.userId))
|
||||
)
|
||||
.map((c) => c.categoryId)
|
||||
.sort()
|
||||
: [];
|
||||
const nextCategoryIds = [...input.categoryIds].sort();
|
||||
|
||||
const materiallyChanged = Boolean(
|
||||
existing &&
|
||||
(existing.serviceRadiusM !== input.serviceRadiusM ||
|
||||
existing.baseLocation.lat !== input.location.lat ||
|
||||
existing.baseLocation.lng !== input.location.lng);
|
||||
(existing.serviceRadiusM !== input.serviceRadiusM ||
|
||||
existing.baseLocation.lat !== input.location.lat ||
|
||||
existing.baseLocation.lng !== input.location.lng ||
|
||||
previousCategoryIds.length !== nextCategoryIds.length ||
|
||||
previousCategoryIds.some((id, i) => id !== nextCategoryIds[i])),
|
||||
);
|
||||
|
||||
/**
|
||||
* Act on it. Computing `materiallyChanged` and returning it to the client
|
||||
* without changing anything server-side is exactly the bug the comment
|
||||
* above was written to prevent: the client is free to ignore the flag.
|
||||
*
|
||||
* Only a currently-verified pro needs demoting. A draft/pending/rejected
|
||||
* profile is already not on the deck, and demoting a `suspended` pro to
|
||||
* pending would quietly undo a moderator's suspension.
|
||||
*/
|
||||
const sendBackForReview = materiallyChanged && existing?.verificationStatus === 'verified';
|
||||
if (sendBackForReview) {
|
||||
assertTransition('verification', 'verified', 'pending');
|
||||
}
|
||||
|
||||
await ctx.db.transaction(async (tx) => {
|
||||
const values = {
|
||||
@@ -83,6 +116,7 @@ export const proRouter = router({
|
||||
baseLocation: input.location,
|
||||
serviceRadiusM: input.serviceRadiusM,
|
||||
updatedAt: new Date(),
|
||||
...(sendBackForReview ? { verificationStatus: 'pending' as const } : {}),
|
||||
};
|
||||
|
||||
await tx
|
||||
@@ -96,9 +130,19 @@ export const proRouter = router({
|
||||
await tx.insert(schema.proCategories).values(
|
||||
input.categoryIds.map((categoryId) => ({ proId: ctx.session.userId, categoryId })),
|
||||
);
|
||||
|
||||
if (sendBackForReview) {
|
||||
await tx.insert(schema.auditLog).values({
|
||||
actorId: ctx.session.userId,
|
||||
action: 'verification.re_review_required',
|
||||
entity: 'pro_profile',
|
||||
entityId: ctx.session.userId,
|
||||
ip: ctx.ip,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return { saved: true, requiresReReview: Boolean(materiallyChanged) };
|
||||
return { saved: true, requiresReReview: sendBackForReview };
|
||||
}),
|
||||
|
||||
/** Attach an uploaded photo. The file itself went straight to R2. */
|
||||
@@ -150,7 +194,7 @@ export const proRouter = router({
|
||||
.values({
|
||||
proId: ctx.session.userId,
|
||||
kind: input.kind,
|
||||
fileUrl: input.fileUrl,
|
||||
fileKey: input.fileKey,
|
||||
issuer: input.issuer ?? null,
|
||||
expiresAt: input.expiresAt ?? null,
|
||||
})
|
||||
|
||||
+1
-1
@@ -85,7 +85,7 @@ CREATE TABLE "credentials" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"pro_id" uuid NOT NULL,
|
||||
"kind" "credential_kind" NOT NULL,
|
||||
"file_url" text NOT NULL,
|
||||
"file_key" text NOT NULL,
|
||||
"issuer" text,
|
||||
"expires_at" timestamp with time zone,
|
||||
"review_status" "review_status" DEFAULT 'pending' NOT NULL,
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"id": "d2669c23-7683-48e2-a271-03f7e5ddcbd1",
|
||||
"id": "6b9ea99a-a893-432a-9bea-ab3e145c97a2",
|
||||
"prevId": "00000000-0000-0000-0000-000000000000",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
@@ -580,8 +580,8 @@
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"file_url": {
|
||||
"name": "file_url",
|
||||
"file_key": {
|
||||
"name": "file_key",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "7",
|
||||
"when": 1787250714989,
|
||||
"tag": "0000_colossal_masked_marvel",
|
||||
"when": 1787252153406,
|
||||
"tag": "0000_material_shadow_king",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
|
||||
@@ -109,7 +109,8 @@ export const credentials = pgTable(
|
||||
.notNull()
|
||||
.references(() => proProfiles.userId, { onDelete: 'cascade' }),
|
||||
kind: credentialKind('kind').notNull(),
|
||||
fileUrl: text('file_url').notNull(),
|
||||
/** R2 object key. Private — resolve with a signed GET, never a public URL. */
|
||||
fileKey: text('file_key').notNull(),
|
||||
issuer: text('issuer'),
|
||||
expiresAt: timestamp('expires_at', { withTimezone: true }),
|
||||
reviewStatus: reviewStatus('review_status').notNull().default('pending'),
|
||||
|
||||
@@ -5,3 +5,4 @@ export * from './ranking';
|
||||
export * from './cancellation';
|
||||
export * from './schemas';
|
||||
export * from './email';
|
||||
export * from './phone';
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Phone identity.
|
||||
*
|
||||
* Phone is the primary identity on this platform, which makes its *string form*
|
||||
* load-bearing: `users.phone` carries a UNIQUE constraint, bans are enforced per
|
||||
* account, and duplicate detection matches on it. If "+34600111222" and
|
||||
* "0034 600 111 222" can both be stored, then one handset holds two distinct
|
||||
* "unique" accounts — which defeats the constraint, lets a banned user return,
|
||||
* and hides the duplicate from `findPossibleDuplicates`.
|
||||
*
|
||||
* So there is exactly one accepted stored form: E.164, no spaces, no separators.
|
||||
* Normalise on the way in, reject anything that cannot be normalised.
|
||||
*/
|
||||
|
||||
/** E.164: a leading +, a nonzero leading digit, and 8–15 digits total. */
|
||||
const E164 = /^\+[1-9]\d{7,14}$/;
|
||||
|
||||
export function isE164(value: string): boolean {
|
||||
return E164.test(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce common user input into E.164, or return null if it cannot be done
|
||||
* unambiguously.
|
||||
*
|
||||
* Handles the shapes people actually type: spaces, hyphens, parentheses and dots
|
||||
* as separators, and a `00` international prefix instead of `+`. It deliberately
|
||||
* does NOT guess a country code for a bare national number — "600111222" is
|
||||
* meaningless without knowing the country, and silently assuming one would
|
||||
* attach a real person's account to the wrong number.
|
||||
*/
|
||||
export function toE164(input: string | null | undefined): string | null {
|
||||
if (!input) return null;
|
||||
|
||||
// Strip everything a human might use as a separator.
|
||||
let s = input.trim().replace(/[\s().-]/g, '');
|
||||
if (s.length === 0) return null;
|
||||
|
||||
// "0034..." is the same as "+34..."
|
||||
if (s.startsWith('00')) s = `+${s.slice(2)}`;
|
||||
|
||||
// A bare national number is ambiguous — refuse rather than guess a country.
|
||||
if (!s.startsWith('+')) return null;
|
||||
|
||||
if (!/^\+\d+$/.test(s)) return null;
|
||||
return isE164(s) ? s : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Last four digits, for display ("••• ••• 222"). Never render a full number
|
||||
* belonging to someone other than the viewer.
|
||||
*/
|
||||
export function phoneLast4(e164: string): string {
|
||||
return e164.slice(-4);
|
||||
}
|
||||
@@ -109,7 +109,12 @@ export type SendMessageInput = z.infer<typeof sendMessageSchema>;
|
||||
|
||||
export const credentialSchema = z.object({
|
||||
kind: z.enum(['id', 'licence', 'insurance']),
|
||||
fileUrl: z.string().url(),
|
||||
/**
|
||||
* An R2 object KEY, not a URL. Credential documents are private — they are
|
||||
* never served publicly, so there is no URL to store. Admins read them
|
||||
* through a short-lived signed GET.
|
||||
*/
|
||||
fileKey: z.string().min(1).max(500),
|
||||
issuer: z.string().max(120).optional(),
|
||||
expiresAt: z.coerce.date().optional(),
|
||||
});
|
||||
|
||||
@@ -99,7 +99,11 @@ const PAYMENT_GRAPH: Graph<PaymentStatus> = {
|
||||
const VERIFICATION_GRAPH: Graph<VerificationStatus> = {
|
||||
draft: ['pending'],
|
||||
pending: ['verified', 'rejected'],
|
||||
verified: ['suspended'],
|
||||
// 'pending' is reachable from 'verified' because a material profile edit
|
||||
// (trade, base location, service radius) sends a live pro back for re-review.
|
||||
// Without this edge the re-review in pro.upsertProfile is not representable
|
||||
// and a verified plumber could silently become a verified electrician.
|
||||
verified: ['suspended', 'pending'],
|
||||
rejected: ['pending'],
|
||||
suspended: ['verified', 'rejected'],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isE164, phoneLast4, toE164 } from '../src/phone';
|
||||
|
||||
/**
|
||||
* These are security tests, not formatting tests. `users.phone` is UNIQUE and
|
||||
* bans are per-account, so any pair of inputs that normalises to two different
|
||||
* strings for one real handset is a way to hold two accounts and to escape a ban.
|
||||
*/
|
||||
describe('toE164', () => {
|
||||
it('passes through an already-normalised number', () => {
|
||||
expect(toE164('+34600111222')).toBe('+34600111222');
|
||||
});
|
||||
|
||||
it('collapses every separator style a human types to ONE stored form', () => {
|
||||
const forms = [
|
||||
'+34 600 111 222',
|
||||
'+34-600-111-222',
|
||||
'+34 (600) 111.222',
|
||||
' +34600111222 ',
|
||||
'0034600111222',
|
||||
'0034 600 111 222',
|
||||
];
|
||||
const normalised = new Set(forms.map(toE164));
|
||||
expect(normalised).toEqual(new Set(['+34600111222']));
|
||||
});
|
||||
|
||||
it('refuses a bare national number rather than guessing a country', () => {
|
||||
// Guessing would attach one person's account to another person's number.
|
||||
expect(toE164('600111222')).toBeNull();
|
||||
expect(toE164('0600111222')).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects junk, empties and letters', () => {
|
||||
expect(toE164(null)).toBeNull();
|
||||
expect(toE164(undefined)).toBeNull();
|
||||
expect(toE164('')).toBeNull();
|
||||
expect(toE164(' ')).toBeNull();
|
||||
expect(toE164('+34600ABC222')).toBeNull();
|
||||
expect(toE164('not a phone')).toBeNull();
|
||||
});
|
||||
|
||||
it('enforces E.164 length and a nonzero country digit', () => {
|
||||
expect(toE164('+3460011')).toBeNull(); // too short
|
||||
expect(toE164('+3460011122233344')).toBeNull(); // too long
|
||||
expect(toE164('+0600111222')).toBeNull(); // country code cannot start with 0
|
||||
});
|
||||
});
|
||||
|
||||
describe('isE164', () => {
|
||||
it('accepts only the canonical stored form', () => {
|
||||
expect(isE164('+34600111222')).toBe(true);
|
||||
expect(isE164('0034600111222')).toBe(false);
|
||||
expect(isE164('+34 600 111 222')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('phoneLast4', () => {
|
||||
it('returns the last four digits for masked display', () => {
|
||||
expect(phoneLast4('+34600111222')).toBe('1222');
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,9 @@
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": { ".": "./src/index.ts" },
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
@@ -17,6 +19,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^2.1.8"
|
||||
"vitest": "^2.1.8",
|
||||
"@linkder/shared": "workspace:*"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,3 +148,31 @@ describe('configuration', () => {
|
||||
).rejects.toThrow(/not allowed/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('key/URL contract with the API', () => {
|
||||
/**
|
||||
* Regression: credential uploads return an object KEY (they are private and
|
||||
* have no public URL), but the credential schema originally demanded
|
||||
* z.string().url(). The result was that pro onboarding could never be
|
||||
* completed — every document upload failed validation at the last step.
|
||||
*
|
||||
* This asserts the contract in both directions so the two halves cannot drift
|
||||
* apart again.
|
||||
*/
|
||||
it('produces a key that is NOT a URL for private kinds', () => {
|
||||
const key = buildKey('credential', OWNER, 'application/pdf');
|
||||
expect(() => new URL(key)).toThrow();
|
||||
expect(isPrivateKind('credential')).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts that key against the credential schema', async () => {
|
||||
const { credentialSchema } = await import('@linkder/shared');
|
||||
const key = buildKey('credential', OWNER, 'application/pdf');
|
||||
expect(credentialSchema.safeParse({ kind: 'insurance', fileKey: key }).success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects an empty key rather than storing a dangling reference', async () => {
|
||||
const { credentialSchema } = await import('@linkder/shared');
|
||||
expect(credentialSchema.safeParse({ kind: 'insurance', fileKey: '' }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user