@proteinjs/user-server 1.24.0 → 1.24.2

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.
@@ -0,0 +1,175 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { builtinModules } from 'module';
4
+ import ts from 'typescript';
5
+
6
+ const PACKAGE_DIR = path.resolve(__dirname, '..');
7
+
8
+ type PackageManifest = {
9
+ types: string;
10
+ dependencies?: Record<string, string>;
11
+ peerDependencies?: Record<string, string>;
12
+ };
13
+
14
+ /** One bare module specifier named by a public declaration file. */
15
+ type DeclarationImport = {
16
+ /** The specifier as written (`@scope/name/sub`, `name`, `node:fs`). */
17
+ specifier: string;
18
+ /** The package a consumer resolves it from (`@scope/name`, `name`); `node:` stripped. */
19
+ packageName: string;
20
+ /** The declaration file naming it, relative to the package. */
21
+ file: string;
22
+ /** How it is named: an import / export clause, an `import('x')` type, or a `/// <reference types>`. */
23
+ via: 'import' | 'import()' | 'reference types';
24
+ };
25
+
26
+ /**
27
+ * The emitted declaration files a consumer's compiler reads — every `.d.ts` reachable from the
28
+ * package's `types` entry through relative imports, exports and `/// <reference path>`
29
+ * directives — and every bare module specifier those files name: import / export … from,
30
+ * `import type`, `import('x')` type nodes, `import x = require('x')`, `/// <reference types="x" />`.
31
+ * Read from the built `dist` with TypeScript's own parser (a doc comment that mentions `'users'`
32
+ * is not an import), so the suite runs after `npm run build`.
33
+ */
34
+ class PublicDeclarationSurface {
35
+ readonly files: string[] = [];
36
+ readonly imports: DeclarationImport[] = [];
37
+ private seen = new Set<string>();
38
+
39
+ constructor(
40
+ private packageDir: string,
41
+ typesEntry: string
42
+ ) {
43
+ this.walk(path.resolve(packageDir, typesEntry));
44
+ }
45
+
46
+ /** The distinct packages the surface names, as a consumer resolves them. */
47
+ packageNames(): string[] {
48
+ return Array.from(new Set(this.imports.map((entry) => entry.packageName))).sort();
49
+ }
50
+
51
+ /** `@scope/name/sub` -> `@scope/name`; `name/sub` -> `name`; `node:fs` -> `fs`. */
52
+ static packageNameOf(specifier: string): string {
53
+ const bare = specifier.startsWith('node:') ? specifier.slice('node:'.length) : specifier;
54
+ const parts = bare.split('/');
55
+ return bare.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
56
+ }
57
+
58
+ private walk(file: string) {
59
+ if (this.seen.has(file)) {
60
+ return;
61
+ }
62
+ this.seen.add(file);
63
+ if (!fs.existsSync(file)) {
64
+ throw new Error(`public declaration file missing: ${path.relative(this.packageDir, file)} — build first`);
65
+ }
66
+ this.files.push(file);
67
+ const source = ts.createSourceFile(file, fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
68
+ for (const reference of source.referencedFiles) {
69
+ this.walk(this.declarationFileFor(file, reference.fileName));
70
+ }
71
+ for (const reference of source.typeReferenceDirectives) {
72
+ this.record(file, reference.fileName, 'reference types');
73
+ }
74
+ const visit = (node: ts.Node) => {
75
+ const specifier = this.specifierOf(node);
76
+ if (specifier) {
77
+ if (specifier.text.startsWith('.')) {
78
+ this.walk(this.declarationFileFor(file, specifier.text));
79
+ } else {
80
+ this.record(file, specifier.text, specifier.via);
81
+ }
82
+ }
83
+ ts.forEachChild(node, visit);
84
+ };
85
+ visit(source);
86
+ }
87
+
88
+ private specifierOf(node: ts.Node): { text: string; via: DeclarationImport['via'] } | undefined {
89
+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier) {
90
+ return ts.isStringLiteral(node.moduleSpecifier) ? { text: node.moduleSpecifier.text, via: 'import' } : undefined;
91
+ }
92
+ if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
93
+ const { expression } = node.moduleReference;
94
+ return ts.isStringLiteral(expression) ? { text: expression.text, via: 'import' } : undefined;
95
+ }
96
+ if (ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {
97
+ const { literal } = node.argument;
98
+ return ts.isStringLiteral(literal) ? { text: literal.text, via: 'import()' } : undefined;
99
+ }
100
+ return undefined;
101
+ }
102
+
103
+ private record(file: string, specifier: string, via: DeclarationImport['via']) {
104
+ this.imports.push({
105
+ specifier,
106
+ packageName: PublicDeclarationSurface.packageNameOf(specifier),
107
+ file: path.relative(this.packageDir, file),
108
+ via,
109
+ });
110
+ }
111
+
112
+ /** A relative specifier's declaration file: `x.d.ts`, else `x/index.d.ts`; a `.d.ts` path as is. */
113
+ private declarationFileFor(from: string, relative: string): string {
114
+ const target = path.resolve(path.dirname(from), relative);
115
+ const candidates = relative.endsWith('.d.ts') ? [target] : [`${target}.d.ts`, path.join(target, 'index.d.ts')];
116
+ const found = candidates.find((candidate) => fs.existsSync(candidate));
117
+ if (!found) {
118
+ throw new Error(
119
+ `${path.relative(this.packageDir, from)} names ${relative}, but none of ${candidates
120
+ .map((candidate) => path.relative(this.packageDir, candidate))
121
+ .join(', ')} exists`
122
+ );
123
+ }
124
+ return found;
125
+ }
126
+ }
127
+
128
+ /**
129
+ * The law: a package's public declarations resolve against its own `dependencies` and
130
+ * `peerDependencies` (and node's builtins) alone — never a devDependency, never a package reached
131
+ * only through another dependency's tree. A consumer that type-checks this package then sees the
132
+ * same types whether its copy is installed from the registry (devDependencies absent) or linked
133
+ * from a checkout (devDependencies present), and the same whether or not a transitive package
134
+ * happens to hoist beside it.
135
+ */
136
+ describe('the public declaration surface resolves against the declared dependencies alone', () => {
137
+ const manifest = JSON.parse(fs.readFileSync(path.join(PACKAGE_DIR, 'package.json'), 'utf8')) as PackageManifest;
138
+ const declared = new Set([
139
+ ...Object.keys(manifest.dependencies ?? {}),
140
+ ...Object.keys(manifest.peerDependencies ?? {}),
141
+ ]);
142
+ const builtins = new Set(builtinModules);
143
+ const surface = new PublicDeclarationSurface(PACKAGE_DIR, manifest.types);
144
+
145
+ /** `name` is declared as itself or as its DefinitelyTyped package (`@types/name`, `@types/scope__name`). */
146
+ const isDeclared = (packageName: string) => {
147
+ const typesName = packageName.startsWith('@')
148
+ ? `@types/${packageName.slice(1).replace('/', '__')}`
149
+ : `@types/${packageName}`;
150
+ return declared.has(packageName) || declared.has(typesName);
151
+ };
152
+ /** A builtin module, or the `node` types that `/// <reference types="node" />` names for them. */
153
+ const isBuiltin = (entry: DeclarationImport) =>
154
+ builtins.has(entry.packageName) || (entry.via === 'reference types' && entry.packageName === 'node');
155
+
156
+ it('reads the whole surface from the types entry (the control: the walk sees files and their imports)', () => {
157
+ const relativeFiles = surface.files.map((file) => path.relative(PACKAGE_DIR, file));
158
+ expect(relativeFiles).toContain(path.normalize('dist/index.d.ts'));
159
+ expect(relativeFiles).toContain(path.normalize('dist/src/emails/AccountDeletionEmailConfigs.d.ts'));
160
+ expect(relativeFiles.length).toBeGreaterThanOrEqual(10);
161
+ expect(surface.packageNames()).toEqual(
162
+ expect.arrayContaining(['@proteinjs/reflection', '@proteinjs/user', 'moment'])
163
+ );
164
+ });
165
+
166
+ it('names no package outside dependencies / peerDependencies / node builtins', () => {
167
+ const undeclared = surface.imports
168
+ .filter((entry) => !isBuiltin(entry) && !isDeclared(entry.packageName))
169
+ .map(
170
+ (entry) =>
171
+ `${entry.file} names '${entry.specifier}' (${entry.via}) — ${entry.packageName} is not in dependencies or peerDependencies`
172
+ );
173
+ expect(undeclared).toEqual([]);
174
+ });
175
+ });
@@ -0,0 +1,126 @@
1
+ import { Db, Reference, StringColumn, Table, getDb, getDbAsSystem, getTables } from '@proteinjs/db';
2
+ import { TransactionContext } from '@proteinjs/db-transaction-context';
3
+ import { getDropTestTable } from '@proteinjs/db-driver-spanner/test';
4
+ import { SourceRepository } from '@proteinjs/reflection';
5
+ import { SharedRecord, User, getSharedDb, tables, withSharedRecordColumns } from '@proteinjs/user';
6
+ import { UserServerTestEnvironment } from './UserServerTestEnvironment';
7
+
8
+ interface SharedNote extends SharedRecord {
9
+ title?: string | null;
10
+ }
11
+
12
+ class SharedNoteTable extends Table<SharedNote> {
13
+ name = 'user_test_shared_note_grant_memo';
14
+ auth: Table<SharedNote>['auth'] = {
15
+ db: { all: 'authenticated' },
16
+ service: { all: 'authenticated' },
17
+ };
18
+ columns = withSharedRecordColumns<SharedNote>({
19
+ title: new StringColumn('title'),
20
+ });
21
+ }
22
+
23
+ const testEnv = new UserServerTestEnvironment();
24
+ const noteTable = new SharedNoteTable() as Table<SharedNote>;
25
+
26
+ type SourceRepositoryInternals = { objectCache: Record<string, unknown[]> };
27
+
28
+ /**
29
+ * The shared-record insert guard asks the caller's grant on the permission source ONCE PER
30
+ * TRANSACTION per scope, not once per row: a transaction that attaches many rows to one scope — a
31
+ * multi-row insert of a subtree, several child rows in one unit — proves the grant with one grant-table
32
+ * read and reuses it for every later row. Outside a transaction every insert still asks (nothing is
33
+ * remembered across requests), and a caller with no grant is refused on the first row inside a
34
+ * transaction exactly as before — the memo only ever shortens a proof it has already made.
35
+ */
36
+ describe('SharedRecord insert guard — one grant read per scope per transaction', () => {
37
+ const dropTestTable = getDropTestTable(testEnv.spannerDriver);
38
+ let owner: User;
39
+ let stranger: User;
40
+ let root: SharedNote;
41
+
42
+ /** The grant-table reads a window makes, counted at the db layer (every guard ask is one query). */
43
+ const grantReadsDuring = async <T>(act: () => Promise<T>): Promise<{ result: T; grantReads: number }> => {
44
+ const query = jest.spyOn(Db.prototype, 'query');
45
+ try {
46
+ const result = await act();
47
+ const grantReads = query.mock.calls.filter(([table]) => table.name === tables.AccessGrant.name).length;
48
+ return { result, grantReads };
49
+ } finally {
50
+ query.mockRestore();
51
+ }
52
+ };
53
+
54
+ const childRow = (n: number): SharedNote =>
55
+ ({
56
+ title: `child ${n}`,
57
+ permissionSource: new Reference(noteTable.name, root.id),
58
+ permissionSourceTable: noteTable.name,
59
+ }) as SharedNote;
60
+
61
+ beforeAll(async () => {
62
+ await testEnv.beforeAll();
63
+ // The ambient transaction context the db's runTransaction seeds and the guard reads (the
64
+ // generated source graph is not loaded under jest, so the implementation is seeded by hand).
65
+ (SourceRepository.get() as unknown as SourceRepositoryInternals).objectCache[
66
+ '@proteinjs/db/DefaultTransactionContextFactory'
67
+ ] = [new TransactionContext()];
68
+ (getTables() as Table<any>[]).push(noteTable);
69
+ await testEnv.spannerDriver.getTableManager().loadTable(noteTable);
70
+ const db = getDbAsSystem();
71
+ await db.delete(tables.AccessGrant, {});
72
+ await db.delete(tables.User, {});
73
+ owner = await testEnv.createUser({ name: 'Memo Owner', email: 'memo-owner@test.local' });
74
+ stranger = await testEnv.createUser({ name: 'Memo Stranger', email: 'memo-stranger@test.local' });
75
+ // The scope root, born as the owner: the framework confers the owner grant after the insert.
76
+ testEnv.actAs(owner);
77
+ root = await getSharedDb().insert(noteTable, { title: 'the document' } as SharedNote);
78
+ }, 180000);
79
+
80
+ afterAll(async () => {
81
+ await dropTestTable(noteTable);
82
+ await testEnv.afterAll();
83
+ }, 120000);
84
+
85
+ test('five rows attached to one scope in one transaction: one grant read, five rows landed', async () => {
86
+ testEnv.actAs(owner);
87
+ const { grantReads } = await grantReadsDuring(() =>
88
+ getDb().runTransaction(async () => {
89
+ for (let n = 1; n <= 5; n++) {
90
+ await getSharedDb().insert(noteTable, childRow(n));
91
+ }
92
+ })
93
+ );
94
+ expect(grantReads).toBe(1);
95
+ const landed = await getDbAsSystem().query(noteTable, { permissionSource: root.id });
96
+ expect(
97
+ landed
98
+ .filter((row) => row.title?.startsWith('child '))
99
+ .map((row) => row.title)
100
+ .sort()
101
+ ).toEqual(['child 1', 'child 2', 'child 3', 'child 4', 'child 5']);
102
+ });
103
+
104
+ test('outside a transaction every insert asks: three lone inserts, three grant reads', async () => {
105
+ testEnv.actAs(owner);
106
+ const { grantReads } = await grantReadsDuring(async () => {
107
+ for (let n = 9; n <= 11; n++) {
108
+ await getSharedDb().insert(noteTable, childRow(n));
109
+ }
110
+ });
111
+ expect(grantReads).toBe(3);
112
+ });
113
+
114
+ test('a caller with no grant is refused on the first row inside a transaction; nothing lands', async () => {
115
+ testEnv.actAs(stranger);
116
+ const before = (await getDbAsSystem().query(noteTable, { permissionSource: root.id })).length;
117
+ await expect(
118
+ getDb().runTransaction(async () => {
119
+ await getSharedDb().insert(noteTable, childRow(12));
120
+ await getSharedDb().insert(noteTable, childRow(13));
121
+ })
122
+ ).rejects.toThrow(/does not have write access/);
123
+ const after = (await getDbAsSystem().query(noteTable, { permissionSource: root.id })).length;
124
+ expect(after).toBe(before);
125
+ });
126
+ });