adula 2.2.0 → 2.3.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 (132) hide show
  1. package/README.md +1 -1
  2. package/build/agent/capabilities.md +2 -3
  3. package/build/agent/skills/adula-frontend-design/SKILL.md +5 -3
  4. package/build/commands/adula_assistant_prune.d.ts +10 -0
  5. package/build/commands/adula_assistant_prune.js +12 -0
  6. package/build/commands/backup_open.d.ts +16 -0
  7. package/build/commands/backup_open.js +48 -0
  8. package/build/commands/backup_restore_test.js +3 -0
  9. package/build/commands/backup_seal.d.ts +12 -0
  10. package/build/commands/backup_seal.js +36 -0
  11. package/build/commands/backup_services.d.ts +3 -1
  12. package/build/commands/doctor.js +18 -1
  13. package/build/commands/install.js +6 -0
  14. package/build/commands/main.d.ts +2 -2
  15. package/build/commands/main.js +6 -0
  16. package/build/commands/resource_migration.js +12 -3
  17. package/build/commands/resource_snapshot.js +18 -4
  18. package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
  19. package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
  20. package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
  21. package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
  22. package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
  23. package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
  24. package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
  25. package/build/database/migrations/1770000000056_appearance.js +10 -0
  26. package/build/index.d.ts +36 -6
  27. package/build/index.js +18 -3
  28. package/build/src/admin/controller.js +18 -4
  29. package/build/src/admin/resource/editor.d.ts +1 -0
  30. package/build/src/admin/resource/editor.js +26 -4
  31. package/build/src/admin/resource/export.d.ts +21 -4
  32. package/build/src/admin/resource/export.js +117 -36
  33. package/build/src/admin/resource/lifecycle.d.ts +2 -0
  34. package/build/src/admin/resource/query.d.ts +14 -3
  35. package/build/src/admin/resource/query.js +98 -11
  36. package/build/src/admin/resource/read.d.ts +3 -0
  37. package/build/src/admin/resource/read.js +75 -14
  38. package/build/src/admin/resource/shared.d.ts +16 -0
  39. package/build/src/admin/resource/shared.js +47 -4
  40. package/build/src/admin/resource/write.js +37 -8
  41. package/build/src/admin/resource_service.d.ts +17 -3
  42. package/build/src/admin/resource_service.js +16 -2
  43. package/build/src/admin/resource_tools.d.ts +111 -0
  44. package/build/src/admin/resource_tools.js +139 -0
  45. package/build/src/ai/assistant.d.ts +100 -0
  46. package/build/src/ai/assistant.js +487 -0
  47. package/build/src/ai/client.d.ts +49 -0
  48. package/build/src/ai/client.js +85 -0
  49. package/build/src/ai/prompt.d.ts +23 -0
  50. package/build/src/ai/prompt.js +83 -0
  51. package/build/src/ai/settings.d.ts +56 -0
  52. package/build/src/ai/settings.js +214 -0
  53. package/build/src/ai/usage.d.ts +16 -0
  54. package/build/src/ai/usage.js +33 -0
  55. package/build/src/appearance/appearance.d.ts +134 -0
  56. package/build/src/appearance/appearance.js +461 -0
  57. package/build/src/appearance/colors.d.ts +43 -0
  58. package/build/src/appearance/colors.js +99 -0
  59. package/build/src/appearance/logo.d.ts +32 -0
  60. package/build/src/appearance/logo.js +112 -0
  61. package/build/src/auth/actor_store.d.ts +5 -1
  62. package/build/src/auth/actor_store.js +8 -4
  63. package/build/src/backups/archive.d.ts +52 -0
  64. package/build/src/backups/archive.js +362 -0
  65. package/build/src/backups/cloud_backups.d.ts +133 -0
  66. package/build/src/backups/cloud_backups.js +650 -0
  67. package/build/src/backups/doctor.d.ts +7 -0
  68. package/build/src/backups/doctor.js +55 -0
  69. package/build/src/backups/providers.d.ts +81 -0
  70. package/build/src/backups/providers.js +470 -0
  71. package/build/src/collaboration/assignments.d.ts +24 -2
  72. package/build/src/collaboration/assignments.js +88 -32
  73. package/build/src/collaboration/record_collaboration.d.ts +19 -1
  74. package/build/src/collaboration/record_collaboration.js +109 -37
  75. package/build/src/collaboration/shared.d.ts +10 -2
  76. package/build/src/collaboration/shared.js +14 -1
  77. package/build/src/commands/capabilities.js +1 -1
  78. package/build/src/commands/doctor.d.ts +10 -0
  79. package/build/src/commands/doctor.js +31 -1
  80. package/build/src/commands/snapshot.d.ts +14 -0
  81. package/build/src/commands/snapshot.js +23 -0
  82. package/build/src/core/administrators.js +19 -3
  83. package/build/src/core/avatar_image.d.ts +33 -0
  84. package/build/src/core/avatar_image.js +278 -0
  85. package/build/src/core/mail_settings.d.ts +83 -0
  86. package/build/src/core/mail_settings.js +274 -0
  87. package/build/src/core/mail_test.d.ts +16 -0
  88. package/build/src/core/mail_test.js +81 -6
  89. package/build/src/core/message_templates.d.ts +8 -0
  90. package/build/src/core/message_templates.js +12 -3
  91. package/build/src/core/roles.js +24 -7
  92. package/build/src/core/saved_views.js +55 -24
  93. package/build/src/core/settings.d.ts +2 -2
  94. package/build/src/core/settings.js +15 -4
  95. package/build/src/core/ui_preferences.d.ts +6 -0
  96. package/build/src/core/ui_preferences.js +12 -1
  97. package/build/src/core/user_avatars.d.ts +79 -0
  98. package/build/src/core/user_avatars.js +186 -0
  99. package/build/src/core/user_preferences.d.ts +36 -0
  100. package/build/src/core/user_preferences.js +125 -0
  101. package/build/src/core/users.d.ts +2 -0
  102. package/build/src/core/users.js +4 -2
  103. package/build/src/database/schema.d.ts +46 -0
  104. package/build/src/database/schema.js +182 -0
  105. package/build/src/database/schema_diff.d.ts +16 -2
  106. package/build/src/database/schema_diff.js +40 -7
  107. package/build/src/integrations/api_client.js +18 -3
  108. package/build/src/integrations/imports.d.ts +16 -4
  109. package/build/src/integrations/imports.js +36 -8
  110. package/build/src/integrations/openapi.js +15 -4
  111. package/build/src/integrations/outbound.d.ts +43 -0
  112. package/build/src/integrations/outbound.js +98 -17
  113. package/build/src/integrations/print.d.ts +2 -1
  114. package/build/src/integrations/print.js +7 -3
  115. package/build/src/integrations/print_templates.js +3 -1
  116. package/build/src/integrations/xlsx.d.ts +41 -0
  117. package/build/src/integrations/xlsx.js +519 -0
  118. package/build/src/languages/ar.js +22 -0
  119. package/build/src/languages/ar_ui.d.ts +143 -14
  120. package/build/src/languages/ar_ui.js +145 -14
  121. package/build/src/languages/en.js +22 -0
  122. package/build/src/languages/en_ui.js +144 -14
  123. package/build/src/lists/dashboards.d.ts +42 -0
  124. package/build/src/lists/dashboards.js +49 -0
  125. package/build/src/mcp/tools.js +9 -104
  126. package/build/src/resource/define_resource.js +7 -0
  127. package/build/src/resource/types.d.ts +9 -0
  128. package/build/src/workflows/delegations.d.ts +15 -1
  129. package/build/src/workflows/delegations.js +49 -10
  130. package/build/src/workflows/engine.d.ts +11 -0
  131. package/build/src/workflows/engine.js +29 -7
  132. package/package.json +5 -1
@@ -0,0 +1,55 @@
1
+ import { parseBackupKey } from './archive.js';
2
+ /**
3
+ * Readiness of downloadable and cloud backups (ADR 051). Every part is optional: a missing key
4
+ * or OAuth client is reported as not configured, never as a failure. A malformed key or a
5
+ * half-configured client is a failure, because the deployment meant to set it.
6
+ */
7
+ export function diagnoseCloudBackups(env) {
8
+ const findings = [];
9
+ const key = env.BACKUP_ENCRYPTION_KEY;
10
+ if (!key)
11
+ findings.push({
12
+ check: 'backup.encryption_key',
13
+ status: 'info',
14
+ message: 'BACKUP_ENCRYPTION_KEY is not configured: encrypted downloads and Drive/OneDrive backups are off',
15
+ });
16
+ else {
17
+ let valid = true;
18
+ try {
19
+ parseBackupKey(key);
20
+ }
21
+ catch {
22
+ valid = false;
23
+ }
24
+ findings.push({
25
+ check: 'backup.encryption_key',
26
+ status: valid ? 'pass' : 'fail',
27
+ message: valid
28
+ ? 'BACKUP_ENCRYPTION_KEY is set; keep an offline copy, archives cannot be opened without it'
29
+ : 'BACKUP_ENCRYPTION_KEY must be the base64 encoding of exactly 32 random bytes',
30
+ });
31
+ }
32
+ for (const [check, label, id, secret] of [
33
+ [
34
+ 'backup.google_drive',
35
+ 'Google Drive',
36
+ 'BACKUP_GOOGLE_CLIENT_ID',
37
+ 'BACKUP_GOOGLE_CLIENT_SECRET',
38
+ ],
39
+ ['backup.onedrive', 'OneDrive', 'BACKUP_MICROSOFT_CLIENT_ID', 'BACKUP_MICROSOFT_CLIENT_SECRET'],
40
+ ]) {
41
+ const present = [env[id], env[secret]].filter(Boolean).length;
42
+ findings.push({
43
+ check,
44
+ status: present === 1 ? 'fail' : present === 2 && !key ? 'warn' : present ? 'pass' : 'info',
45
+ message: present === 0
46
+ ? `${label} backups are not configured`
47
+ : present === 1
48
+ ? `${label} needs both ${id} and ${secret}`
49
+ : key
50
+ ? `${label} OAuth client is configured; register the redirect URI <APP_URL>/admin/backups/oauth/${check === 'backup.google_drive' ? 'google' : 'onedrive'}/callback`
51
+ : `${label} is configured, but uploads stay off until BACKUP_ENCRYPTION_KEY is set`,
52
+ });
53
+ }
54
+ return findings;
55
+ }
@@ -0,0 +1,81 @@
1
+ import { type OutboundOptions } from '../integrations/outbound.js';
2
+ /**
3
+ * Backup destinations reached through OAuth (ADR 051). Each client asks for the narrowest
4
+ * scope its API offers: Google Drive `drive.file` (only files this application created) and
5
+ * OneDrive `Files.ReadWrite.AppFolder` (only the application's own folder). Endpoints are set
6
+ * in code by the host; tests point them at local fakes. Tokens never appear in errors.
7
+ */
8
+ export type BackupProvider = 'google' | 'onedrive';
9
+ export type BackupProviderErrorCategory = 'revoked' | 'auth' | 'quota' | 'integrity' | 'response' | 'timeout' | 'blocked-target' | 'dns' | 'connect' | 'tls' | 'secret' | `http-status:${number}`;
10
+ /** A provider failure with a stored category; the message never holds a token or URL query. */
11
+ export declare class BackupProviderError extends Error {
12
+ category: BackupProviderErrorCategory;
13
+ constructor(category: BackupProviderErrorCategory, message?: string);
14
+ }
15
+ export type BackupProviderClient = {
16
+ provider: BackupProvider;
17
+ /** The provider's consent page for an administrator; state and PKCE are the caller's. */
18
+ authorizeUrl(input: {
19
+ state: string;
20
+ codeChallenge: string;
21
+ redirectUri: string;
22
+ }): string;
23
+ exchange(input: {
24
+ code: string;
25
+ verifier: string;
26
+ redirectUri: string;
27
+ }): Promise<{
28
+ refreshToken: string;
29
+ accountLabel: string | null;
30
+ }>;
31
+ refresh(refreshToken: string): Promise<{
32
+ accessToken: string;
33
+ refreshToken?: string;
34
+ }>;
35
+ upload(input: {
36
+ file: string;
37
+ name: string;
38
+ size: number;
39
+ sha256: string;
40
+ accessToken: string;
41
+ signal?: AbortSignal;
42
+ }): Promise<{
43
+ remoteId: string;
44
+ size: number;
45
+ }>;
46
+ /** Revokes a refresh token at the provider, where the provider offers it. */
47
+ revoke?(refreshToken: string): Promise<void>;
48
+ };
49
+ export type GoogleDriveEndpoints = {
50
+ auth: string;
51
+ token: string;
52
+ api: string;
53
+ upload: string;
54
+ revoke: string;
55
+ };
56
+ export type OneDriveEndpoints = {
57
+ authority: string;
58
+ graph: string;
59
+ };
60
+ export type BackupProviderOptions = {
61
+ clientId: string;
62
+ clientSecret: string;
63
+ outbound?: OutboundOptions;
64
+ /** Bytes per upload request. */
65
+ chunkSize?: number;
66
+ /** Per-request timeout. */
67
+ timeoutMs?: number;
68
+ retries?: number;
69
+ };
70
+ /** A PKCE verifier and its S256 challenge. */
71
+ export declare function pkcePair(): {
72
+ verifier: string;
73
+ challenge: string;
74
+ };
75
+ export declare function googleDriveProvider(options: BackupProviderOptions & {
76
+ endpoints?: Partial<GoogleDriveEndpoints>;
77
+ }): BackupProviderClient;
78
+ export declare function oneDriveProvider(options: BackupProviderOptions & {
79
+ tenant?: string;
80
+ endpoints?: Partial<OneDriveEndpoints>;
81
+ }): BackupProviderClient;
@@ -0,0 +1,470 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { open } from 'node:fs/promises';
3
+ import { OutboundResponseTooLargeError, OutboundTargetError, guardOutboundUrl, outboundErrorCategory, pinnedRequest, } from '../integrations/outbound.js';
4
+ /** A provider failure with a stored category; the message never holds a token or URL query. */
5
+ export class BackupProviderError extends Error {
6
+ category;
7
+ constructor(category, message = `Backup provider request failed (${category})`) {
8
+ super(message);
9
+ this.category = category;
10
+ }
11
+ }
12
+ const GOOGLE_SCOPE = 'https://www.googleapis.com/auth/drive.file';
13
+ const ONEDRIVE_SCOPE = 'Files.ReadWrite.AppFolder offline_access';
14
+ const GOOGLE_FOLDER = 'AdulaJS backups';
15
+ const RESPONSE_LIMIT = 1024 * 1024;
16
+ const GOOGLE_CHUNK = 8 * 1024 * 1024;
17
+ const ONEDRIVE_CHUNK = 10 * 1024 * 1024;
18
+ /** A PKCE verifier and its S256 challenge. */
19
+ export function pkcePair() {
20
+ const verifier = randomBytes(32).toString('base64url');
21
+ const challenge = createHash('sha256').update(verifier).digest('base64url');
22
+ return { verifier, challenge };
23
+ }
24
+ function http(options) {
25
+ const timeoutMs = options.timeoutMs ?? 60_000;
26
+ return async (value, call) => {
27
+ const signals = [AbortSignal.timeout(timeoutMs), ...(call.signal ? [call.signal] : [])];
28
+ try {
29
+ const { url, target } = await guardOutboundUrl(value, options.outbound);
30
+ return await pinnedRequest(url, {
31
+ method: call.method,
32
+ headers: call.headers ?? {},
33
+ body: call.body,
34
+ signal: AbortSignal.any(signals),
35
+ target,
36
+ maxResponseBytes: RESPONSE_LIMIT,
37
+ });
38
+ }
39
+ catch (error) {
40
+ if (error instanceof BackupProviderError)
41
+ throw error;
42
+ if (error instanceof OutboundResponseTooLargeError)
43
+ throw new BackupProviderError('response');
44
+ if (error instanceof OutboundTargetError)
45
+ throw new BackupProviderError(error.category);
46
+ throw new BackupProviderError(outboundErrorCategory(error));
47
+ }
48
+ };
49
+ }
50
+ function json(response) {
51
+ try {
52
+ const value = JSON.parse(response.body.toString('utf8'));
53
+ if (value && typeof value === 'object')
54
+ return value;
55
+ }
56
+ catch { }
57
+ throw new BackupProviderError('response');
58
+ }
59
+ function header(response, name) {
60
+ const value = response.headers[name.toLowerCase()];
61
+ return Array.isArray(value) ? value[0] : value;
62
+ }
63
+ /** Classifies a token endpoint refusal; `invalid_grant` means consent was withdrawn. */
64
+ function tokenFailure(response) {
65
+ let error;
66
+ try {
67
+ error = JSON.parse(response.body.toString('utf8'))?.error;
68
+ }
69
+ catch { }
70
+ if (error === 'invalid_grant')
71
+ return new BackupProviderError('revoked');
72
+ if (response.status === 400 || response.status === 401)
73
+ return new BackupProviderError('auth');
74
+ return new BackupProviderError(`http-status:${response.status}`);
75
+ }
76
+ function statusFailure(response) {
77
+ if (response.status === 401)
78
+ return new BackupProviderError('auth');
79
+ if (response.status === 507)
80
+ return new BackupProviderError('quota');
81
+ if (response.status === 403) {
82
+ const text = response.body.toString('utf8');
83
+ if (/storageQuotaExceeded|quotaExceeded|quotaLimitReached/i.test(text))
84
+ return new BackupProviderError('quota');
85
+ }
86
+ return new BackupProviderError(`http-status:${response.status}`);
87
+ }
88
+ function form(values) {
89
+ return new URLSearchParams(values).toString();
90
+ }
91
+ async function tokenRequest(send, url, values) {
92
+ const response = await send(url, {
93
+ method: 'POST',
94
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' },
95
+ body: form(values),
96
+ });
97
+ if (response.status !== 200)
98
+ throw tokenFailure(response);
99
+ const body = json(response);
100
+ if (typeof body.access_token !== 'string' || !body.access_token)
101
+ throw new BackupProviderError('response');
102
+ return body;
103
+ }
104
+ /** Reads `length` bytes of a file at `offset`. */
105
+ async function readRange(file, offset, length) {
106
+ const handle = await open(file, 'r');
107
+ try {
108
+ const buffer = Buffer.alloc(length);
109
+ const { bytesRead } = await handle.read(buffer, 0, length, offset);
110
+ return buffer.subarray(0, bytesRead);
111
+ }
112
+ finally {
113
+ await handle.close();
114
+ }
115
+ }
116
+ /** Retries a resumable upload step after transient failures, at most `retries` times. */
117
+ async function transient(retries, step) {
118
+ for (let attempt = 0;; attempt++) {
119
+ try {
120
+ return await step(attempt);
121
+ }
122
+ catch (error) {
123
+ const category = error instanceof BackupProviderError ? error.category : 'connect';
124
+ const retryable = category === 'connect' ||
125
+ category === 'timeout' ||
126
+ /^http-status:(5\d\d|429)$/.test(category);
127
+ if (!retryable || attempt >= retries)
128
+ throw error;
129
+ await new Promise((resolve) => setTimeout(resolve, Math.min(200 * 2 ** attempt, 5000)));
130
+ }
131
+ }
132
+ }
133
+ /** A session URL returned by the provider must stay on an allowed origin. */
134
+ function sessionUrl(value, allowedOrigin) {
135
+ if (!value)
136
+ throw new BackupProviderError('response');
137
+ let url;
138
+ try {
139
+ url = new URL(value);
140
+ }
141
+ catch {
142
+ throw new BackupProviderError('response');
143
+ }
144
+ if (url.username || url.password)
145
+ throw new BackupProviderError('blocked-target');
146
+ if (allowedOrigin && url.origin !== allowedOrigin)
147
+ throw new BackupProviderError('blocked-target');
148
+ return url;
149
+ }
150
+ /** The next byte the provider expects, from a Range header `bytes=0-N`. */
151
+ function nextFromRange(value) {
152
+ if (!value)
153
+ return 0;
154
+ const match = /^bytes=0-(\d+)$/.exec(value.trim());
155
+ if (!match)
156
+ throw new BackupProviderError('response');
157
+ return Number(match[1]) + 1;
158
+ }
159
+ export function googleDriveProvider(options) {
160
+ const endpoints = {
161
+ auth: 'https://accounts.google.com/o/oauth2/v2/auth',
162
+ token: 'https://oauth2.googleapis.com/token',
163
+ api: 'https://www.googleapis.com',
164
+ upload: 'https://www.googleapis.com',
165
+ revoke: 'https://oauth2.googleapis.com/revoke',
166
+ ...options.endpoints,
167
+ };
168
+ const send = http(options);
169
+ const chunkSize = options.chunkSize ?? GOOGLE_CHUNK;
170
+ if (chunkSize % (256 * 1024) !== 0)
171
+ throw new RangeError('Drive chunks are multiples of 256 KiB');
172
+ const retries = options.retries ?? 5;
173
+ const bearer = (token) => ({ Authorization: `Bearer ${token}` });
174
+ async function folder(accessToken, signal) {
175
+ const query = `name = '${GOOGLE_FOLDER}' and mimeType = 'application/vnd.google-apps.folder' and trashed = false`;
176
+ const search = new URL('/drive/v3/files', endpoints.api);
177
+ search.searchParams.set('q', query);
178
+ search.searchParams.set('fields', 'files(id)');
179
+ search.searchParams.set('spaces', 'drive');
180
+ const found = await send(search, { method: 'GET', headers: bearer(accessToken), signal });
181
+ if (found.status !== 200)
182
+ throw statusFailure(found);
183
+ const existing = json(found).files?.[0]?.id;
184
+ if (typeof existing === 'string' && existing)
185
+ return existing;
186
+ const created = await send(new URL('/drive/v3/files?fields=id', endpoints.api), {
187
+ method: 'POST',
188
+ headers: { ...bearer(accessToken), 'Content-Type': 'application/json' },
189
+ body: JSON.stringify({ name: GOOGLE_FOLDER, mimeType: 'application/vnd.google-apps.folder' }),
190
+ signal,
191
+ });
192
+ if (created.status !== 200)
193
+ throw statusFailure(created);
194
+ const id = json(created).id;
195
+ if (typeof id !== 'string' || !id)
196
+ throw new BackupProviderError('response');
197
+ return id;
198
+ }
199
+ return {
200
+ provider: 'google',
201
+ authorizeUrl({ state, codeChallenge, redirectUri }) {
202
+ const url = new URL(endpoints.auth);
203
+ url.search = form({
204
+ client_id: options.clientId,
205
+ redirect_uri: redirectUri,
206
+ response_type: 'code',
207
+ scope: GOOGLE_SCOPE,
208
+ access_type: 'offline',
209
+ prompt: 'consent',
210
+ include_granted_scopes: 'false',
211
+ state,
212
+ code_challenge: codeChallenge,
213
+ code_challenge_method: 'S256',
214
+ });
215
+ return url.toString();
216
+ },
217
+ async exchange({ code, verifier, redirectUri }) {
218
+ const body = await tokenRequest(send, endpoints.token, {
219
+ grant_type: 'authorization_code',
220
+ code,
221
+ code_verifier: verifier,
222
+ redirect_uri: redirectUri,
223
+ client_id: options.clientId,
224
+ client_secret: options.clientSecret,
225
+ });
226
+ if (typeof body.refresh_token !== 'string' || !body.refresh_token)
227
+ throw new BackupProviderError('response');
228
+ if (typeof body.scope === 'string' && !body.scope.split(' ').includes(GOOGLE_SCOPE))
229
+ throw new BackupProviderError('auth');
230
+ let accountLabel = null;
231
+ try {
232
+ const about = await send(new URL('/drive/v3/about?fields=user(emailAddress,displayName)', endpoints.api), { method: 'GET', headers: bearer(body.access_token) });
233
+ if (about.status === 200) {
234
+ const user = json(about).user ?? {};
235
+ const label = user.emailAddress ?? user.displayName;
236
+ accountLabel = typeof label === 'string' ? label.slice(0, 320) : null;
237
+ }
238
+ }
239
+ catch { }
240
+ return { refreshToken: body.refresh_token, accountLabel };
241
+ },
242
+ async refresh(refreshToken) {
243
+ const body = await tokenRequest(send, endpoints.token, {
244
+ grant_type: 'refresh_token',
245
+ refresh_token: refreshToken,
246
+ client_id: options.clientId,
247
+ client_secret: options.clientSecret,
248
+ });
249
+ return {
250
+ accessToken: body.access_token,
251
+ refreshToken: typeof body.refresh_token === 'string' ? body.refresh_token : undefined,
252
+ };
253
+ },
254
+ async upload({ file, name, size, sha256, accessToken, signal }) {
255
+ const parent = await folder(accessToken, signal);
256
+ const start = new URL('/upload/drive/v3/files', endpoints.upload);
257
+ start.search = form({ uploadType: 'resumable', fields: 'id,size,sha256Checksum' });
258
+ const session = await transient(retries, async () => {
259
+ const response = await send(start, {
260
+ method: 'POST',
261
+ headers: {
262
+ ...bearer(accessToken),
263
+ 'Content-Type': 'application/json; charset=UTF-8',
264
+ 'X-Upload-Content-Type': 'application/octet-stream',
265
+ 'X-Upload-Content-Length': String(size),
266
+ },
267
+ body: JSON.stringify({ name, parents: [parent], mimeType: 'application/octet-stream' }),
268
+ signal,
269
+ });
270
+ if (response.status !== 200)
271
+ throw statusFailure(response);
272
+ return sessionUrl(header(response, 'location'), new URL(endpoints.upload).origin);
273
+ });
274
+ const finish = (response) => {
275
+ const item = json(response);
276
+ if (typeof item.id !== 'string' || Number(item.size) !== size)
277
+ throw new BackupProviderError('integrity');
278
+ if (typeof item.sha256Checksum === 'string' && item.sha256Checksum.toLowerCase() !== sha256)
279
+ throw new BackupProviderError('integrity');
280
+ return { remoteId: item.id, size };
281
+ };
282
+ let offset = 0;
283
+ let result = null;
284
+ while (!result) {
285
+ result = await transient(retries, async (attempt) => {
286
+ if (attempt > 0) {
287
+ // Ask where the upload stands before sending more.
288
+ const probe = await send(session, {
289
+ method: 'PUT',
290
+ headers: { ...bearer(accessToken), 'Content-Range': `bytes */${size}` },
291
+ signal,
292
+ });
293
+ if (probe.status === 200 || probe.status === 201)
294
+ return finish(probe);
295
+ if (probe.status !== 308)
296
+ throw statusFailure(probe);
297
+ offset = nextFromRange(header(probe, 'range'));
298
+ }
299
+ const length = Math.min(chunkSize, size - offset);
300
+ const bytes = length > 0 ? await readRange(file, offset, length) : Buffer.alloc(0);
301
+ if (bytes.length !== length)
302
+ throw new BackupProviderError('integrity');
303
+ const range = size === 0 ? `bytes */0` : `bytes ${offset}-${offset + length - 1}/${size}`;
304
+ const response = await send(session, {
305
+ method: 'PUT',
306
+ headers: { ...bearer(accessToken), 'Content-Range': range },
307
+ body: bytes,
308
+ signal,
309
+ });
310
+ if (response.status === 200 || response.status === 201)
311
+ return finish(response);
312
+ if (response.status !== 308)
313
+ throw statusFailure(response);
314
+ const next = nextFromRange(header(response, 'range'));
315
+ if (next <= offset && length > 0)
316
+ throw new BackupProviderError('response');
317
+ offset = next;
318
+ return null;
319
+ });
320
+ }
321
+ return result;
322
+ },
323
+ async revoke(refreshToken) {
324
+ await send(endpoints.revoke, {
325
+ method: 'POST',
326
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
327
+ body: form({ token: refreshToken }),
328
+ });
329
+ },
330
+ };
331
+ }
332
+ export function oneDriveProvider(options) {
333
+ const endpoints = {
334
+ authority: 'https://login.microsoftonline.com',
335
+ graph: 'https://graph.microsoft.com/v1.0',
336
+ ...options.endpoints,
337
+ };
338
+ const tenant = options.tenant || 'common';
339
+ if (!/^[A-Za-z0-9.-]+$/.test(tenant))
340
+ throw new RangeError('Invalid Microsoft tenant');
341
+ const authorize = `${endpoints.authority}/${tenant}/oauth2/v2.0/authorize`;
342
+ const token = `${endpoints.authority}/${tenant}/oauth2/v2.0/token`;
343
+ const graph = endpoints.graph.replace(/\/$/, '');
344
+ const send = http(options);
345
+ const chunkSize = options.chunkSize ?? ONEDRIVE_CHUNK;
346
+ if (chunkSize % (320 * 1024) !== 0)
347
+ throw new RangeError('OneDrive chunks are multiples of 320 KiB');
348
+ const retries = options.retries ?? 5;
349
+ const bearer = (value) => ({ Authorization: `Bearer ${value}` });
350
+ const nextExpected = (body) => {
351
+ const first = body.nextExpectedRanges?.[0];
352
+ const match = typeof first === 'string' ? /^(\d+)-/.exec(first) : null;
353
+ if (!match)
354
+ throw new BackupProviderError('response');
355
+ return Number(match[1]);
356
+ };
357
+ return {
358
+ provider: 'onedrive',
359
+ authorizeUrl({ state, codeChallenge, redirectUri }) {
360
+ const url = new URL(authorize);
361
+ url.search = form({
362
+ client_id: options.clientId,
363
+ redirect_uri: redirectUri,
364
+ response_type: 'code',
365
+ response_mode: 'query',
366
+ scope: ONEDRIVE_SCOPE,
367
+ prompt: 'select_account',
368
+ state,
369
+ code_challenge: codeChallenge,
370
+ code_challenge_method: 'S256',
371
+ });
372
+ return url.toString();
373
+ },
374
+ async exchange({ code, verifier, redirectUri }) {
375
+ const body = await tokenRequest(send, token, {
376
+ grant_type: 'authorization_code',
377
+ code,
378
+ code_verifier: verifier,
379
+ redirect_uri: redirectUri,
380
+ client_id: options.clientId,
381
+ client_secret: options.clientSecret,
382
+ scope: ONEDRIVE_SCOPE,
383
+ });
384
+ if (typeof body.refresh_token !== 'string' || !body.refresh_token)
385
+ throw new BackupProviderError('response');
386
+ let accountLabel = null;
387
+ try {
388
+ const drive = await send(`${graph}/me/drive?$select=owner`, {
389
+ method: 'GET',
390
+ headers: bearer(body.access_token),
391
+ });
392
+ if (drive.status === 200) {
393
+ const user = json(drive).owner?.user ?? {};
394
+ const label = user.email ?? user.displayName;
395
+ accountLabel = typeof label === 'string' ? label.slice(0, 320) : null;
396
+ }
397
+ }
398
+ catch { }
399
+ return { refreshToken: body.refresh_token, accountLabel };
400
+ },
401
+ async refresh(refreshToken) {
402
+ const body = await tokenRequest(send, token, {
403
+ grant_type: 'refresh_token',
404
+ refresh_token: refreshToken,
405
+ client_id: options.clientId,
406
+ client_secret: options.clientSecret,
407
+ scope: ONEDRIVE_SCOPE,
408
+ });
409
+ return {
410
+ accessToken: body.access_token,
411
+ refreshToken: typeof body.refresh_token === 'string' ? body.refresh_token : undefined,
412
+ };
413
+ },
414
+ async upload({ file, name, size, accessToken, signal }) {
415
+ const create = `${graph}/me/drive/special/approot:/${encodeURIComponent(name)}:/createUploadSession`;
416
+ const session = await transient(retries, async () => {
417
+ const response = await send(create, {
418
+ method: 'POST',
419
+ headers: { ...bearer(accessToken), 'Content-Type': 'application/json' },
420
+ body: JSON.stringify({ item: { '@microsoft.graph.conflictBehavior': 'fail' } }),
421
+ signal,
422
+ });
423
+ if (response.status !== 200)
424
+ throw statusFailure(response);
425
+ // The upload URL is pre-authorized and may be on another host: no bearer token goes there.
426
+ return sessionUrl(json(response).uploadUrl, null);
427
+ });
428
+ const finish = (response) => {
429
+ const item = json(response);
430
+ if (typeof item.id !== 'string' || Number(item.size) !== size)
431
+ throw new BackupProviderError('integrity');
432
+ return { remoteId: item.id, size };
433
+ };
434
+ if (size === 0)
435
+ throw new BackupProviderError('integrity');
436
+ let offset = 0;
437
+ let result = null;
438
+ while (!result) {
439
+ result = await transient(retries, async (attempt) => {
440
+ if (attempt > 0) {
441
+ const probe = await send(session, { method: 'GET', signal });
442
+ if (probe.status !== 200)
443
+ throw statusFailure(probe);
444
+ offset = nextExpected(json(probe));
445
+ }
446
+ const length = Math.min(chunkSize, size - offset);
447
+ const bytes = await readRange(file, offset, length);
448
+ if (bytes.length !== length || length <= 0)
449
+ throw new BackupProviderError('integrity');
450
+ const response = await send(session, {
451
+ method: 'PUT',
452
+ headers: { 'Content-Range': `bytes ${offset}-${offset + length - 1}/${size}` },
453
+ body: bytes,
454
+ signal,
455
+ });
456
+ if (response.status === 200 || response.status === 201)
457
+ return finish(response);
458
+ if (response.status !== 202)
459
+ throw statusFailure(response);
460
+ const next = nextExpected(json(response));
461
+ if (next <= offset)
462
+ throw new BackupProviderError('response');
463
+ offset = next;
464
+ return null;
465
+ });
466
+ }
467
+ return result;
468
+ },
469
+ };
470
+ }
@@ -13,8 +13,12 @@ export type Assignment = {
13
13
  recordTitle: string | null;
14
14
  assigneeId: number;
15
15
  assigneeName: string | null;
16
+ /** The assignee's versioned picture URL, or null without one (ADR 050). */
17
+ assigneeAvatarUrl?: string | null;
16
18
  assignedBy: number | null;
17
19
  assignedByName: string | null;
20
+ /** Who assigned it: their versioned picture URL, or null without one (ADR 050). */
21
+ assignedByAvatarUrl?: string | null;
18
22
  kind: string;
19
23
  title: string;
20
24
  note: string | null;
@@ -45,13 +49,19 @@ export type Assignment = {
45
49
  } | null;
46
50
  /** The SLA deadline of an approval with one (ISO time); dueOn stays its calendar date. */
47
51
  dueAt?: string | null;
48
- /** The SLA state of an open approval with a deadline. */
52
+ /**
53
+ * The SLA state of an open item: an approval's SLA deadline (dueAt), or a manual task's
54
+ * due date (dueOn), overdue after its last day in the system time zone. Null otherwise.
55
+ */
49
56
  sla?: SlaState | null;
50
57
  };
51
58
  export type AssignmentPage = {
52
59
  data: Assignment[];
53
60
  nextCursor: string | null;
54
- /** Open items of every kind. */
61
+ /**
62
+ * Open items of every kind the user may act on, on records they can still read: the
63
+ * number of items the open list shows (counted over the newest 1000 records).
64
+ */
55
65
  open: number;
56
66
  /** Open approval steps among them. 1.2; optional for compatibility. */
57
67
  approvals?: number;
@@ -75,6 +85,7 @@ export type AssignmentOptions = {
75
85
  * re-checks the record so lost access hides the task instead of leaking it.
76
86
  */
77
87
  export declare class Assignments {
88
+ #private;
78
89
  private db;
79
90
  private resources;
80
91
  private actors;
@@ -115,6 +126,15 @@ export declare class Assignments {
115
126
  dueSoonAt?: Date | null;
116
127
  escalatedAt?: Date | null;
117
128
  }): Promise<any>;
129
+ /**
130
+ * The numbers the open list shows: every item the user may act on today, own or held
131
+ * through a delegation (ADR 044), on records the user can still open. The «مهامي» badge
132
+ * reads this, so the badge and the list agree (#156).
133
+ */
134
+ openCounts(actor: Actor): Promise<{
135
+ open: number;
136
+ approvals: number;
137
+ }>;
118
138
  /** The signed-in user's own tasks, open first; records they can no longer read are hidden. */
119
139
  mine(actor: Actor, options?: {
120
140
  status?: string;
@@ -160,5 +180,7 @@ export declare class Assignments {
160
180
  private today;
161
181
  private closeNote;
162
182
  private label;
183
+ /** permits() on a given connection: denial (403/404) is false, other errors propagate. */
184
+ private viewable;
163
185
  private canView;
164
186
  }