Skip to content

Commit

Permalink
Merge pull request #17940 from mozilla/fix-auth-tsconfig
Browse files Browse the repository at this point in the history
bug(auth): Typescript not checking all files
  • Loading branch information
dschom authored Nov 6, 2024
2 parents 089872d + e3e2ba8 commit 5af8f3f
Show file tree
Hide file tree
Showing 24 changed files with 174 additions and 142 deletions.
10 changes: 5 additions & 5 deletions packages/fxa-auth-server/lib/l10n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,22 +66,22 @@ class Localizer {
return generateBundles;
}

async getLocalizerDeps(acceptLanguage: string) {
const currentLocales = parseAcceptLanguage(acceptLanguage);
const selectedLocale = determineLocale(acceptLanguage);
async getLocalizerDeps(acceptLanguage?: string) {
const currentLocales = parseAcceptLanguage(acceptLanguage || '');
const selectedLocale = determineLocale(acceptLanguage || '');
const messages = await this.fetchMessages(currentLocales);
const generateBundles = this.createBundleGenerator(messages);
return { currentLocales, messages, generateBundles, selectedLocale };
}

async setupDomLocalizer(acceptLanguage: string) {
async setupDomLocalizer(acceptLanguage?: string) {
const { currentLocales, generateBundles, selectedLocale } =
await this.getLocalizerDeps(acceptLanguage);
const l10n = new DOMLocalization(currentLocales, generateBundles);
return { l10n, selectedLocale };
}

async setupLocalizer(acceptLanguage: string) {
async setupLocalizer(acceptLanguage?: string) {
const { currentLocales, generateBundles, selectedLocale } =
await this.getLocalizerDeps(acceptLanguage);
const l10n = new Localization(currentLocales, generateBundles);
Expand Down
6 changes: 4 additions & 2 deletions packages/fxa-auth-server/lib/metrics/glean/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ type MetricsData = {
uid?: string;
reason?: string;
oauthClientId?: string;
scopes?: string;
scopes?: string | Array<string>;
};

type AdditionalMetricsCallback = (
Expand Down Expand Up @@ -265,7 +265,7 @@ export function gleanMetrics(config: ConfigType) {
scopes: metrics.scopes
? Array.isArray(metrics.scopes)
? metrics.scopes.sort().join(',')
: metrics.scopes
: metrics.scopes.split(',').sort().join(',')
: '',
}),
}),
Expand Down Expand Up @@ -305,6 +305,8 @@ export function gleanMetrics(config: ConfigType) {
};
}

export type GleanMetricsType = ReturnType<typeof gleanMetrics>;

const routePathToErrorPingFnMap = {
'/account/create': 'registration.error',
'/account/login': 'login.error',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@ export class AppStoreRetryableError extends Error {
super(errorMessage);
this.name = 'AppStoreRetryableError';
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
}
26 changes: 13 additions & 13 deletions packages/fxa-auth-server/lib/payments/stripe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ export class StripeHelper extends StripeHelperBase {
* Fetch all active tax rates.
*/
async fetchAllTaxRates() {
const taxRates = [];
const taxRates = new Array<Stripe.TaxRate>();
for await (const taxRate of this.stripe.taxRates.list({ active: true })) {
taxRates.push(taxRate);
}
Expand Down Expand Up @@ -1534,7 +1534,7 @@ export class StripeHelper extends StripeHelperBase {
async *fetchOpenInvoices(
created: Stripe.InvoiceListParams['created'],
customerId?: string
) {
): AsyncGenerator<Stripe.Invoice> {
for await (const invoice of this.stripe.invoices.list({
customer: customerId,
limit: 100,
Expand Down Expand Up @@ -1907,7 +1907,7 @@ export class StripeHelper extends StripeHelperBase {
);
});
const iapType = getIapPurchaseType(purchases[0]);
const purchasedPrices = [];
const purchasedPrices = new Array<string>();
for (const price of prices) {
const purchaseIds = this.priceToIapIdentifiers(price, iapType);
if (purchaseIds.some((id) => purchasedIds.includes(id))) {
Expand Down Expand Up @@ -2482,7 +2482,7 @@ export class StripeHelper extends StripeHelperBase {
async formatSubscriptionsForSupport(
subscriptions: Stripe.ApiList<Stripe.Subscription>
) {
const subs = [];
const subs = new Array<any>();
for (const sub of subscriptions.data) {
const plan = singlePlan(sub);
if (!plan) {
Expand All @@ -2503,8 +2503,8 @@ export class StripeHelper extends StripeHelperBase {
}
const product_name = product.name;

let previous_product = null;
let plan_changed = null;
let previous_product: string | null = null;
let plan_changed: number | null = null;

if (sub.metadata.previous_plan_id !== undefined) {
const previousPlan = await this.findAbbrevPlanById(
Expand Down Expand Up @@ -2618,8 +2618,8 @@ export class StripeHelper extends StripeHelperBase {

// if the invoice does not have the deprecated discount property but has a discount ID in discounts
// expand the discount
let discountType = null;
let discountDuration = null;
let discountType: Stripe.Coupon.Duration | null = null;
let discountDuration: number | null = null;

if (invoice.discount) {
discountType = invoice.discount.coupon.duration;
Expand Down Expand Up @@ -2801,7 +2801,7 @@ export class StripeHelper extends StripeHelperBase {
return [];
}

const formattedSubscriptions = [];
const formattedSubscriptions = new Array<FormattedSubscriptionForEmail>();

for (const subscription of customer.subscriptions.data) {
if (ACTIVE_SUBSCRIPTION_STATUSES.includes(subscription.status)) {
Expand Down Expand Up @@ -3183,10 +3183,10 @@ export class StripeHelper extends StripeHelperBase {
}

async extractCustomerDefaultPaymentDetails(customer: Stripe.Customer) {
let lastFour = null;
let cardType = null;
let country = null;
let postalCode = null;
let lastFour: string | null = null;
let cardType: string | null = null;
let country: string | null = null;
let postalCode: string | null = null;

if (customer.invoice_settings.default_payment_method) {
// Post-SCA customer with a default PaymentMethod
Expand Down
6 changes: 3 additions & 3 deletions packages/fxa-auth-server/lib/routes/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ export class AccountHandler {
);

// Handle authPWVersion2 credentials
let password2 = undefined;
let password2: any | undefined = undefined;
let verifyHashVersion2 = undefined;
let wrapWrapKb = await random.hex(32);
let wrapWrapKbVersion2 = undefined;
Expand All @@ -164,8 +164,8 @@ export class AccountHandler {
authSalt,
this.config.verifierVersion
);
verifyHashVersion2 = await password2.verifyHash();
wrapWrapKbVersion2 = await password2.wrap(wrapKbVersion2);
verifyHashVersion2 = await password2?.verifyHash();
wrapWrapKbVersion2 = await password2?.wrap(wrapKbVersion2);

// When version 2 credentials are supplied, the wrapKb will also be supplied.
// This is necessary to the same kB values are produced for both passwords.
Expand Down
12 changes: 6 additions & 6 deletions packages/fxa-auth-server/lib/routes/password.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ module.exports = function (

await customs.check(request, email, 'passwordChange');

let keyFetchToken = undefined;
let keyFetchToken2 = undefined;
let passwordChangeToken = undefined;
let keyFetchToken: any | undefined = undefined;
let keyFetchToken2: any | undefined = undefined;
let passwordChangeToken: any | undefined = undefined;

try {
const emailRecord = await db.accountRecord(email);
Expand Down Expand Up @@ -315,7 +315,7 @@ module.exports = function (

// For the time being we store both passwords in the DB. authPW is created
// with the old quickStretch and authPWVersion2 is created with improved 'quick' stretch.
let password2 = undefined;
let password2: any | undefined = undefined;
let verifyHashVersion2 = undefined;
let wrapWrapKbVersion2 = undefined;
if (authPWVersion2) {
Expand All @@ -325,8 +325,8 @@ module.exports = function (
verifierVersion,
2
);
verifyHashVersion2 = await password2.verifyHash();
wrapWrapKbVersion2 = await password2.wrap(wrapKbVersion2);
verifyHashVersion2 = await password2?.verifyHash();
wrapWrapKbVersion2 = await password2?.wrap(wrapKbVersion2);
}

await db.deletePasswordChangeToken(passwordChangeToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ export class PayPalHandler extends StripeWebhookHandler {
);

const nowSeconds = msToSec(Date.now());
const invoices = [];
const invoices = new Array<any>();
for await (const invoice of this.stripeHelper.fetchOpenInvoices(
nowSeconds,
customer.id
Expand Down
10 changes: 8 additions & 2 deletions packages/fxa-auth-server/lib/routes/subscriptions/stripe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,13 @@ export class StripeHandler {
const customer = await this.stripeHelper.fetchCustomer(uid, [
'subscriptions',
]);
const activeSubscriptions = [];
const activeSubscriptions = new Array<{
uid: string;
productId: string | Stripe.Product | Stripe.DeletedProduct | null;
subscriptionId: string;
createdAt: number;
cancelledAt: number | null;
}>();

if (customer && customer.subscriptions) {
for (const subscription of customer.subscriptions.data) {
Expand Down Expand Up @@ -388,7 +394,7 @@ export class StripeHandler {
string
>;

let customer = undefined;
let customer: Stripe.Customer | void = undefined;
if (request.auth.credentials) {
const { uid, email } = await handleAuth(this.db, request.auth, true);
await this.customs.check(request, email, 'previewInvoice');
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
type MjIncludeTag = { path: string; inline: boolean; type: string };
type MjIncludeTag = { path?: string; inline: boolean; type?: string };

/**
* Important! At the current momement, mjml-browser does not support <mj-include>.
Expand Down Expand Up @@ -48,7 +48,7 @@ export function transformMjIncludeTags(mjml: string): string {
function extractMjIncludeTags(mjml: string): MjIncludeTag[] {
let chomp = false;
let include = '';
const includes = [];
const includes = new Array<MjIncludeTag>();
mjml
.replace(/<mj-include/g, ' <mj-include')
.split(/\n|\s/g)
Expand Down Expand Up @@ -96,7 +96,7 @@ function parseMjIncludeTag(include: string): MjIncludeTag {

// Convert relative paths. The requests will now be made to the root
// of the webserver.
res.path = res.path.replace(/\.\//, '/');
res.path = res.path?.replace(/\.\//, '/');

return res;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import { Meta } from '@storybook/html';
import { storyWithProps } from '../../storybook-email';
import { MOCK_USER_INFO_TRUNCATED } from '../userInfo/mocks';
import {
MOCK_DEVICE_ALL,
MOCK_DEVICE_BROWSER,
Expand All @@ -24,7 +23,6 @@ const createStory = storyWithProps(
subject: 'N/A',
partial: 'userInfo',
layout: null,
...MOCK_USER_INFO_TRUNCATED,
}
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export default {
const createStory = storyWithProps(
'cadReminderSecond',
'Sent 72 hours after a user clicks "send me a reminder" on the connect another device page.',
cadReminderFirst.CadReminderDefault.args.variables
cadReminderFirst.CadReminderDefault.args?.variables
);

export const CadReminderDefault = createStory();
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,14 @@ export class BrowserRendererBindings extends RendererBindings {
);
}

renderEjs(template: string, context: TemplateContext, body?: string) {
renderEjs(
template: string,
context: Pick<
TemplateContext,
'acceptLanguage' | 'templateValues' | 'layout'
>,
body?: string
) {
return ejs.render(template, { ...context, body: body }, this.opts.ejs);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/fxa-auth-server/lib/senders/renderer/bindings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export type TemplateValues = {

// TODO: better typing for 'template' with enums? from _versions.json
export interface TemplateContext {
acceptLanguage: string;
acceptLanguage?: string;
template: string;
layout?: string;
templateValues?: TemplateValues;
Expand Down
6 changes: 3 additions & 3 deletions packages/fxa-auth-server/lib/senders/renderer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class Renderer extends Localizer {
) {
// l10n will only be undefined in tests
if (!l10n) {
l10n = (await super.setupLocalizer(context.acceptLanguage)).l10n;
l10n = (await super.setupLocalizer(context.acceptLanguage || '')).l10n;
}

const localizedString =
Expand All @@ -61,7 +61,7 @@ class Renderer extends Localizer {
async renderEmail(templateContext: TemplateContext) {
const { acceptLanguage, template, layout } = templateContext;
const { l10n, selectedLocale } = await super.setupDomLocalizer(
acceptLanguage
acceptLanguage || ''
);

const context = {
Expand Down Expand Up @@ -99,7 +99,7 @@ class Renderer extends Localizer {
}

const { text, rootElement } = await this.bindings.renderTemplate(
template,
template || '',
context,
layout
);
Expand Down
2 changes: 1 addition & 1 deletion packages/fxa-auth-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"bump-template-versions": "node scripts/template-version-bump",
"clean": "rimraf dist",
"clean-up-old-ci-stripe-customers": "node -r esbuild-register ./scripts/clean-up-old-ci-stripe-customers.js --limit 1000",
"compile": "tsc --noEmit",
"compile": "yarn install-ejs && tsc --noEmit",
"create-mock-iap": "NODE_ENV=dev FIRESTORE_EMULATOR_HOST=localhost:9090 node -r esbuild-register ./scripts/create-mock-iap-subscriptions.ts",
"audit": "npm audit --json | audit-filter --nsp-config=.nsprc --audit=-",
"glean-generate": "npx glean translate ../fxa-shared/metrics/glean/fxa-backend-pings.yaml ../fxa-shared/metrics/glean/fxa-backend-metrics.yaml -f typescript_server -o lib/metrics/glean",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@ export async function init() {

const options = program.opts();
const rateLimit = parseInt(options.rateLimit);
process.env.NODE_ENV = options.config || 'dev';

const node_env = process.env.NODE_ENV;
if (node_env !== (options.condition || 'dev')) {
throw new Error('Unexpected NODE_ENV ' + node_env);
}

const { log, stripeHelper } = await setupProcessingTaskObjects(
'populate-firestore-customers'
);
Expand Down
4 changes: 2 additions & 2 deletions packages/fxa-auth-server/scripts/prune-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ Exit Codes:
// Start max session pruning
if (maxSessions > 0) {
// Locate large accounts
const targetAccounts = [];
const targetAccounts = new Array<string>();
try {
log.info('finding large accounts', {
maxSessions,
Expand Down Expand Up @@ -268,7 +268,7 @@ Exit Codes:

// Iterate through current set of redis tokens, and remove any that
// don't exist in the sql database anymore.
const orphanedTokens = [];
const orphanedTokens = new Array<string>();
for (const redisSessionTokenId of redisSessionTokenIds) {
const dbSessionTokens = await SessionToken.findByTokenId(
redisSessionTokenId
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export class StripeProductsAndPlansConverter {
metadata: Stripe.Product['metadata'],
metadataKeyPrefix: string
): string[] {
const metadataValues = [];
const metadataValues = new Array<any>();
for (const [metadataKey, metadataValue] of Object.entries(metadata)) {
if (metadataKey.startsWith(metadataKeyPrefix)) {
metadataValues.push(metadataValue);
Expand Down
Loading

0 comments on commit 5af8f3f

Please sign in to comment.