@deveye/types 0.24.5 → 0.25.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.
@@ -66,7 +66,20 @@ export const workspaceLeave = {
66
66
  output: z.object({ workspaceId: z.number().int().positive() })
67
67
  };
68
68
 
69
- /** Exclut un membre de l'espace actif. Réservé au propriétaire. */
69
+ /**
70
+ * Ce qu'un départ emporte avec le membre : les projections qu'il avait réglées
71
+ * entre cet espace et d'autres, dans les deux sens, nommées pour la
72
+ * confirmation. Pour soi-même, ou pour un autre avec `workspace.members`.
73
+ */
74
+ export const workspaceMemberShares = {
75
+ command: 'workspace.memberShares' as const,
76
+ input: z.object({ userId: z.number().int().positive() }),
77
+ output: z.object({
78
+ shares: z.array(z.object({ feature: z.string(), label: z.string() }))
79
+ })
80
+ };
81
+
82
+ /** Exclut un membre de l'espace actif, et retire ses projections avec lui. */
70
83
  export const workspaceRemoveMember = {
71
84
  command: 'workspace.removeMember' as const,
72
85
  input: z.object({ userId: z.number().int().positive() }),
@@ -74,16 +87,54 @@ export const workspaceRemoveMember = {
74
87
  };
75
88
 
76
89
  /**
77
- * Ajoute un membre à l'espace actif, désigné par son adresse. Pas de lien ni
78
- * d'acceptation : le compte existe déjà, et un lien serait un secret
79
- * transmissible de plus.
90
+ * Invite une adresse à rejoindre l'espace actif. La réponse ne dit jamais si un
91
+ * compte porte cette adresse : l'invitation est posée telle quelle, et c'est le
92
+ * compte qui l'accepte (`workspace.acceptInvite`) ou la refuse.
80
93
  */
81
- export const workspaceAddMember = {
82
- command: 'workspace.addMember' as const,
94
+ export const workspaceInvite = {
95
+ command: 'workspace.invite' as const,
83
96
  input: z.object({ email: z.string().email() }),
97
+ output: z.object({})
98
+ };
99
+
100
+ /** Les invitations en attente de l'espace actif, pour qui gère ses membres. */
101
+ export const workspaceInvitations = {
102
+ command: 'workspace.invitations' as const,
103
+ input: z.object({}),
104
+ output: z.object({
105
+ invitations: z.array(
106
+ z.object({
107
+ id: z.number().int().positive(),
108
+ email: z.string(),
109
+ /** Seconds. */
110
+ expiresAt: z.number().int().nonnegative()
111
+ })
112
+ )
113
+ })
114
+ };
115
+
116
+ export const workspaceCancelInvite = {
117
+ command: 'workspace.cancelInvite' as const,
118
+ input: z.object({ invitationId: z.number().int().positive() }),
119
+ output: z.object({ invitationId: z.number().int().positive() })
120
+ };
121
+
122
+ /**
123
+ * Accepte une invitation adressée à l'appelant : il devient membre de l'espace,
124
+ * avec le rôle fixé à l'invitation. L'espace rendu est celui qu'il rejoint.
125
+ */
126
+ export const workspaceAcceptInvite = {
127
+ command: 'workspace.acceptInvite' as const,
128
+ input: z.object({ invitationId: z.number().int().positive() }),
84
129
  output: z.object({ workspace: workspaceSchema })
85
130
  };
86
131
 
132
+ export const workspaceDeclineInvite = {
133
+ command: 'workspace.declineInvite' as const,
134
+ input: z.object({ invitationId: z.number().int().positive() }),
135
+ output: z.object({ invitationId: z.number().int().positive() })
136
+ };
137
+
87
138
  /** Le contenu modifiable d'un rôle. */
88
139
  const roleDraftSchema = z.object({
89
140
  name: z.string().min(1).max(WORKSPACE_ROLE_NAME_MAX),
@@ -157,8 +208,13 @@ export const workspaceCommands = [
157
208
  workspaceAssignRole,
158
209
  workspaceRename,
159
210
  workspaceLeave,
211
+ workspaceMemberShares,
160
212
  workspaceRemoveMember,
161
- workspaceAddMember,
213
+ workspaceInvite,
214
+ workspaceInvitations,
215
+ workspaceCancelInvite,
216
+ workspaceAcceptInvite,
217
+ workspaceDeclineInvite,
162
218
  workspaceAdd,
163
219
  workspaceDelete,
164
220
  workspaceActivate,
package/src/http/auth.ts CHANGED
@@ -46,7 +46,9 @@ export type SessionBundle = z.infer<typeof sessionBundleSchema>;
46
46
 
47
47
  export const loginRequestSchema = z.object({
48
48
  username: z.string().min(1).max(120),
49
- password: z.string().min(1).max(512)
49
+ password: z.string().min(1).max(512),
50
+ /** A federated page's trusted-browser token for this account; a same-origin page holds a cookie instead. */
51
+ trustToken: z.string().max(256).optional()
50
52
  });
51
53
 
52
54
  export type LoginRequest = z.infer<typeof loginRequestSchema>;
@@ -84,33 +86,63 @@ export const changePasswordResponseSchema = z.object({
84
86
 
85
87
  export type ChangePasswordResponse = z.infer<typeof changePasswordResponseSchema>;
86
88
 
89
+ /**
90
+ * What may stand between a correct password and a session, in this order: a
91
+ * code mailed to a browser the account does not know, the authenticator app,
92
+ * a code texted to that browser.
93
+ */
94
+ export const loginStepSchema = z.enum(['email', 'totp', 'sms']);
95
+
96
+ export type LoginStep = z.infer<typeof loginStepSchema>;
97
+
98
+ /** A login waiting for the code of `step`. */
99
+ export const loginPendingSchema = z.object({
100
+ status: z.literal('pending'),
101
+ step: loginStepSchema,
102
+ /** Where the code went, masked (`g•••@gmail.com`, `•• •• •• 12 34`). */
103
+ to: z.string().optional(),
104
+ /** The challenge, for a federated origin (no cookie holds it there). */
105
+ challenge: z.string().optional()
106
+ });
107
+
108
+ export type LoginPending = z.infer<typeof loginPendingSchema>;
109
+
87
110
  /**
88
111
  * The auth flow returns the authenticated user and its workspaces in one shot.
89
112
  * Tokens are delivered as HttpOnly cookies, never in the JSON body, except to a
90
113
  * federated origin (`tokens`, see {@link sessionTokensSchema}).
91
114
  *
92
- * When 2FA is enabled, login first replies with `twoFactorRequired` and an
93
- * interim challenge token (a cookie, or `challenge` for a federated origin); the
94
- * client then posts a TOTP/backup code.
115
+ * A login may first reply `pending`: each code posted to `/login/verify` moves
116
+ * to the next step, until the session opens (`signedIn`).
95
117
  */
96
- export const loginResponseSchema = z.discriminatedUnion('twoFactorRequired', [
118
+ export const loginResponseSchema = z.discriminatedUnion('status', [
97
119
  sessionBundleSchema.extend({
98
- twoFactorRequired: z.literal(false),
99
- tokens: sessionTokensSchema.optional()
120
+ status: z.literal('signedIn'),
121
+ tokens: sessionTokensSchema.optional(),
122
+ /** A federated page's new trusted-browser token, when it asked to be trusted. */
123
+ trustToken: z.string().optional()
100
124
  }),
101
- z.object({ twoFactorRequired: z.literal(true), challenge: z.string().optional() })
125
+ loginPendingSchema
102
126
  ]);
103
127
 
104
128
  export type LoginResponse = z.infer<typeof loginResponseSchema>;
105
129
 
106
- export const twoFactorChallengeRequestSchema = z.object({
107
- /** A 6-digit TOTP code or a recovery backup code. */
130
+ /** `POST /api/auth/login/verify`: the code of the current step. */
131
+ export const loginVerifyRequestSchema = z.object({
132
+ /** Six digits, or a recovery code on the `totp` step. */
108
133
  code: z.string().min(6).max(24),
109
- /** The challenge handed by `/login`, from a federated origin (no cookie holds it there). */
134
+ /** Trust this browser: its next logins skip the mailed and texted codes. */
135
+ trust: z.boolean().optional(),
136
+ /** The challenge handed by `/login`, from a federated origin. */
110
137
  challenge: z.string().max(2048).optional()
111
138
  });
112
139
 
113
- export type TwoFactorChallengeRequest = z.infer<typeof twoFactorChallengeRequestSchema>;
140
+ export type LoginVerifyRequest = z.infer<typeof loginVerifyRequestSchema>;
141
+
142
+ /** `POST /api/auth/login/resend` and `/login/cancel`: only a federated origin names its challenge. */
143
+ export const loginChallengeRequestSchema = z.object({ challenge: z.string().max(2048).optional() });
144
+
145
+ export type LoginChallengeRequest = z.infer<typeof loginChallengeRequestSchema>;
114
146
 
115
147
  /** Body of `/refresh` and `/logout` from a federated origin; a same-origin page sends none. */
116
148
  export const refreshRequestSchema = z.object({ refreshToken: z.string().max(2048) });
package/src/index.ts CHANGED
@@ -526,7 +526,7 @@ export type {
526
526
  } from './domain/project';
527
527
  export { presenceEventSchema } from './domain/presence';
528
528
  export type { PresenceEvent, PresenceRow } from './domain/presence';
529
- export { userRoleSchema } from './domain/role';
529
+ export { canModerate, userRoleSchema } from './domain/role';
530
530
  export type { UserRole } from './domain/role';
531
531
  export {
532
532
  homeFeatureIdSchema,
@@ -546,6 +546,7 @@ export {
546
546
  isFeatureTile,
547
547
  isHomeFolder,
548
548
  isShortcutTile,
549
+ placedFeatureIds,
549
550
  shortcutItemSchema,
550
551
  shortcutPreviewSchema,
551
552
  shortcutTemplateSchema,
@@ -652,7 +653,11 @@ export type {
652
653
  SecrecyWrapMode,
653
654
  UserSecretKeyRow
654
655
  } from './domain/secrecy';
655
- export { workspaceKindSchema, workspaceSchema } from './domain/workspace';
656
+ export {
657
+ WORKSPACE_INVITATION_TTL_SECONDS,
658
+ workspaceKindSchema,
659
+ workspaceSchema
660
+ } from './domain/workspace';
656
661
  export {
657
662
  REMOTE_INSTANCES_MAX,
658
663
  REMOTE_LABEL_MAX,
@@ -690,6 +695,7 @@ export type {
690
695
  } from './domain/workspaceRole';
691
696
  export type {
692
697
  Workspace,
698
+ WorkspaceInvitationRow,
693
699
  WorkspaceKind,
694
700
  WorkspaceMemberRow,
695
701
  WorkspaceRow
@@ -895,6 +901,20 @@ export type {
895
901
  MetricsResolution
896
902
  } from './domain/metrics';
897
903
  export { twoFactorSetupSchema, twoFactorStatusSchema } from './domain/twoFactor';
904
+ export {
905
+ STEP_UP_MINUTES_DEFAULT,
906
+ STEP_UP_MINUTES_MAX,
907
+ STEP_UP_MINUTES_MIN,
908
+ stepUpRequiredDetailsSchema,
909
+ stepUpStatusSchema
910
+ } from './domain/stepUp';
911
+ export type { StepUpRequiredDetails, StepUpStatus } from './domain/stepUp';
912
+ export {
913
+ loginChecksStatusSchema,
914
+ TRUSTED_BROWSER_DAYS,
915
+ trustedBrowserSchema
916
+ } from './domain/loginChecks';
917
+ export type { LoginChecksStatus, TrustedBrowser } from './domain/loginChecks';
898
918
  export type {
899
919
  BackupCodeRow,
900
920
  TwoFactorRow,
@@ -919,6 +939,9 @@ export {
919
939
  adminDeleteUser,
920
940
  adminExternalServices,
921
941
  adminExternalServicesSchema,
942
+ adminFeatureFactSchema,
943
+ adminFeatureStats,
944
+ adminFeatureStatsSchema,
922
945
  adminMaintenanceDismissNotice,
923
946
  adminMaintenanceFeature,
924
947
  adminMaintenanceGet,
@@ -927,12 +950,21 @@ export {
927
950
  adminMaintenanceSeats,
928
951
  adminMaintenanceSignups,
929
952
  adminMaintenanceSite,
953
+ adminPending,
954
+ adminPendingSchema,
930
955
  adminSetUserRole,
931
956
  adminSetUserStatus,
932
957
  adminUserList,
933
958
  adminUserSchema
934
959
  } from './features/admin';
935
- export type { AdminExternalServices, AdminMaintenance, AdminUser } from './features/admin';
960
+ export type {
961
+ AdminExternalServices,
962
+ AdminFeatureFact,
963
+ AdminFeatureStats,
964
+ AdminMaintenance,
965
+ AdminPending,
966
+ AdminUser
967
+ } from './features/admin';
936
968
  export {
937
969
  debugBenchCatalog,
938
970
  debugBenchContextSchema,
@@ -999,8 +1031,13 @@ export {
999
1031
  workspaceCommands,
1000
1032
  workspaceDelete,
1001
1033
  workspaceLeave,
1034
+ workspaceMemberShares,
1002
1035
  workspaceRemoveMember,
1003
- workspaceAddMember,
1036
+ workspaceInvite,
1037
+ workspaceInvitations,
1038
+ workspaceCancelInvite,
1039
+ workspaceAcceptInvite,
1040
+ workspaceDeclineInvite,
1004
1041
  workspaceAssignRole,
1005
1042
  workspaceRename,
1006
1043
  workspaceRoleCreate,
@@ -1030,6 +1067,7 @@ export {
1030
1067
  userExportPartSchema,
1031
1068
  userExportPrepare,
1032
1069
  userExportPreview,
1070
+ userInvitations,
1033
1071
  userPlan,
1034
1072
  userSetAvatar,
1035
1073
  userSetColor,
@@ -1080,6 +1118,18 @@ export {
1080
1118
  notifyRouteSet,
1081
1119
  notifyRouteTest
1082
1120
  } from './features/notify';
1121
+ export { stepUpCommands, stepUpConfirm, stepUpSetInterval, stepUpStatus } from './features/stepUp';
1122
+ export {
1123
+ loginChecksCommands,
1124
+ loginChecksForgetBrowser,
1125
+ loginChecksForgetBrowsers,
1126
+ loginChecksPhoneConfirm,
1127
+ loginChecksPhoneRemove,
1128
+ loginChecksPhoneStart,
1129
+ loginChecksSetEmail,
1130
+ loginChecksSetSms,
1131
+ loginChecksStatus
1132
+ } from './features/loginChecks';
1083
1133
  export {
1084
1134
  twoFactorCommands,
1085
1135
  twoFactorDisable,
@@ -1127,8 +1177,12 @@ export type { FeedbackFilter } from './features/feedback';
1127
1177
  export {
1128
1178
  changePasswordRequestSchema,
1129
1179
  changePasswordResponseSchema,
1180
+ loginChallengeRequestSchema,
1181
+ loginPendingSchema,
1130
1182
  loginRequestSchema,
1131
1183
  loginResponseSchema,
1184
+ loginStepSchema,
1185
+ loginVerifyRequestSchema,
1132
1186
  meResponseSchema,
1133
1187
  passwordSchema,
1134
1188
  refreshRequestSchema,
@@ -1143,14 +1197,17 @@ export {
1143
1197
  signupStatusSchema,
1144
1198
  signupVerifyRequestSchema,
1145
1199
  signupVerifyResponseSchema,
1146
- twoFactorChallengeRequestSchema,
1147
1200
  wsTicketResponseSchema
1148
1201
  } from './http/auth';
1149
1202
  export type {
1150
1203
  ChangePasswordRequest,
1151
1204
  ChangePasswordResponse,
1205
+ LoginChallengeRequest,
1206
+ LoginPending,
1152
1207
  LoginRequest,
1153
1208
  LoginResponse,
1209
+ LoginStep,
1210
+ LoginVerifyRequest,
1154
1211
  MeResponse,
1155
1212
  RefreshRequest,
1156
1213
  RefreshResponse,
@@ -1164,7 +1221,6 @@ export type {
1164
1221
  SignupStatus,
1165
1222
  SignupVerifyRequest,
1166
1223
  SignupVerifyResponse,
1167
- TwoFactorChallengeRequest,
1168
1224
  WsTicketResponse
1169
1225
  } from './http/auth';
1170
1226
  export {
@@ -1475,10 +1475,12 @@ export type AgentServerMessage = z.infer<typeof agentServerMessageSchema>;
1475
1475
 
1476
1476
  /**
1477
1477
  * Signature of a high-impact order, carried next to `command` and `payload` as
1478
- * `sig`. Ed25519 over `command \n nonce \n issuedAt \n` followed by the exact
1479
- * bytes of the payload as sent. The agent verifies it against the key pinned at
1480
- * enrolment, refuses an `issuedAt` more than five minutes off, and refuses a
1481
- * nonce it has already seen.
1478
+ * `sig`. Ed25519 over `command \n deviceId \n nonce \n issuedAt \n` followed
1479
+ * by the exact bytes of the payload as sent. The agent verifies it against the
1480
+ * key pinned at enrolment and its own device id (one key signs for every
1481
+ * machine of a server: without the id, an order signed for one would run on
1482
+ * all), refuses an `issuedAt` more than five minutes off, and refuses a nonce
1483
+ * it has already seen.
1482
1484
  */
1483
1485
  export const orderSignatureSchema = z.object({
1484
1486
  nonce: z.string().length(32),
@@ -1489,21 +1491,36 @@ export type OrderSignature = z.infer<typeof orderSignatureSchema>;
1489
1491
 
1490
1492
  /**
1491
1493
  * The orders the server signs (`ORDER_SIGNING_KEY`) and the agent refuses
1492
- * unsigned: what runs code, writes or deletes files, changes the agent's
1493
- * privileges or its life, drives its containers, or reaches into its network.
1494
- * Mirror of `SIGNED_COMMANDS` in `agent/src/protocol.rs`.
1494
+ * unsigned: what runs code, writes, moves or deletes files, reads their
1495
+ * content, changes the agent's privileges, its life or its token, drives its
1496
+ * containers, reaches into its network, or drives what CloudSync writes.
1497
+ * `sync.applyChunk` is not signed (a chunk per megabyte would exhaust the
1498
+ * nonce window) but only lands in a transfer a signed `sync.applyStart`
1499
+ * opened; `agent.update` is not signed so an agent that predates this format
1500
+ * can still be updated. Mirror of `SIGNED_COMMANDS` in `agent/src/protocol.rs`.
1495
1501
  */
1496
1502
  export const SIGNED_AGENT_COMMANDS: ReadonlySet<string> = new Set([
1497
1503
  AGENT_TERM_OPEN,
1498
1504
  AGENT_FILES_MUTATE,
1499
1505
  AGENT_FILES_UPLOAD,
1506
+ AGENT_FILES_DOWNLOAD,
1507
+ AGENT_FILES_ARCHIVE,
1508
+ AGENT_SYNC_CONFIG,
1509
+ AGENT_SYNC_SCAN,
1510
+ AGENT_SYNC_PUSH,
1511
+ AGENT_SYNC_APPLY_START,
1512
+ AGENT_SYNC_APPLY_DIR,
1513
+ AGENT_SYNC_APPLY_LOCAL,
1514
+ AGENT_SYNC_MOVE,
1515
+ AGENT_SYNC_DELETE,
1500
1516
  AGENT_SERVICE,
1501
1517
  AGENT_POWER,
1502
1518
  AGENT_DESTROY,
1503
1519
  AGENT_PKG_UPGRADE,
1504
1520
  AGENT_LIFECYCLE,
1505
1521
  AGENT_DOCKER_ACTION,
1506
- AGENT_TUNNEL_OPEN
1522
+ AGENT_TUNNEL_OPEN,
1523
+ AGENT_TOKEN_ROTATE
1507
1524
  ]);
1508
1525
 
1509
1526
  /**
@@ -22,7 +22,11 @@ export const ErrorCodeSchema = z.enum([
22
22
  'maintenance',
23
23
  // The server is full for this kind of account: the socket waits in line
24
24
  // (see `domain/admission.ts`). `details` carries `{ position }`.
25
- 'queued'
25
+ 'queued',
26
+ // Driving a machine needs a fresh authenticator code in this session
27
+ // (see `domain/stepUp.ts`). `details` carries `{ twoFactor }`: `false`
28
+ // when the account has no authenticator app to ask a code from.
29
+ 'stepup_required'
26
30
  ]);
27
31
 
28
32
  export type ErrorCode = z.infer<typeof ErrorCodeSchema>;
package/src/sdk/client.ts CHANGED
@@ -55,11 +55,6 @@ export interface AccountViewProps {
55
55
  hint?: string;
56
56
  }
57
57
 
58
- /** Props of {@link FeatureClient.AdminView}. */
59
- export interface AdminViewProps {
60
- close(): void;
61
- }
62
-
63
58
  /**
64
59
  * Your package's `./client` export.
65
60
  */
@@ -74,8 +69,13 @@ export interface FeatureClient {
74
69
  Full?: ComponentType<FeatureViewProps>;
75
70
  /** The view `manifest.accountEntry` opens from the user menu. */
76
71
  AccountView?: ComponentType<AccountViewProps>;
77
- /** The system page `manifest.adminEntry` opens, for a global administrator only. */
78
- AdminView?: ComponentType<AdminViewProps>;
72
+ /**
73
+ * One component per tab of `manifest.adminTabs`, by its id, drawn under
74
+ * the header of the feature administration popup: no title of your own,
75
+ * the popup names your feature and the tab. No props: the data comes from
76
+ * `useResource`, and the commands it sends decide who may read what.
77
+ */
78
+ AdminTabs?: Readonly<Record<string, ComponentType>>;
79
79
  /**
80
80
  * The vignette shown on your card in the home grid's add market and on
81
81
  * your "About" sheet. Without one, the host draws a neutral module mark:
@@ -314,6 +314,25 @@ describe('copie d’un élément', () => {
314
314
  );
315
315
  });
316
316
 
317
+ it('expurge un secret de sa colonne scellée, et refuse une valeur scellée qui ne serait pas du texte', async () => {
318
+ const tree: ItemTree = [
319
+ { ...TREE[0], redact: { content: (plain) => plain.replace('tableau', '•') } }
320
+ ];
321
+ const rows = await exportItemTree(fakeDb(seed()), tree, 1, cipherOf('A'));
322
+ assert.equal(rows.boards[0].content, '•');
323
+
324
+ const target = seed();
325
+ await assert.rejects(
326
+ importItemTree(
327
+ fakeDb(target),
328
+ TREE,
329
+ { boards: [{ id: 1, content: { $wire: 'x' } }] },
330
+ into('B')
331
+ ),
332
+ /Valeur inattendue/
333
+ );
334
+ });
335
+
317
336
  it('refuse un élément que la destination tient déjà sous le même nom', async () => {
318
337
  const tree: ItemTree = [
319
338
  { ...TREE[0], unique: { column: 'name_ref', message: 'Déjà là.' } }
@@ -370,5 +389,9 @@ describe('arbre d’un élément', () => {
370
389
  itemTreeProblem([TREE[0], TREE[1], TREE[2], { ...LABELS, refs: {} }]) ?? '',
371
390
  /scoped/
372
391
  );
392
+ assert.match(
393
+ itemTreeProblem([{ ...TREE[0], redact: { name: (p) => p } }]) ?? '',
394
+ /redacted/
395
+ );
373
396
  });
374
397
  });
package/src/sdk/copy.ts CHANGED
@@ -47,6 +47,15 @@ export interface ItemTreeTable {
47
47
  * indistinguishable from another. Revisit it whenever you add one.
48
48
  */
49
49
  sealed?: readonly string[];
50
+ /**
51
+ * Sealed columns that hold a secret among other data: the copy carries
52
+ * what this returns instead of the clear text (a mail account's servers,
53
+ * without its password), and the copy arrives to be reconnected. A secret
54
+ * held in a column of its own belongs in `omit`. A copy goes through the
55
+ * browser of whoever makes it, who may only read the item: no password or
56
+ * token ever travels.
57
+ */
58
+ redact?: Readonly<Record<string, (plain: string) => string>>;
50
59
  /**
51
60
  * Columns pointing at a row of a table of this tree (this one included),
52
61
  * by that table's name: rewritten to the ids the destination handed out. A
@@ -155,6 +164,12 @@ export function itemTreeProblem(tree: ItemTree): string | null {
155
164
  const bad = names.find((n) => !IDENTIFIER.test(n));
156
165
  if (bad !== undefined) return `${t.table}: "${bad}" is not a plain SQL identifier`;
157
166
  if (seen.has(t.table)) return `${t.table}: listed twice`;
167
+ const unsealed = Object.keys(t.redact ?? {}).find(
168
+ (column) => !(t.sealed ?? []).includes(column)
169
+ );
170
+ if (unsealed !== undefined) {
171
+ return `${t.table}.${unsealed}: only a sealed column is redacted`;
172
+ }
158
173
  if (t.tier && t !== root) return `${t.table}: only the root chooses the tier`;
159
174
  if ((t.orderColumn || t.unique) && (t !== root || !t.workspaceColumn)) {
160
175
  return `${t.table}: orderColumn and unique are for a root that names its workspaceColumn`;
@@ -274,7 +289,7 @@ export async function exportItemTree(
274
289
  `Une ligne de ${t.table} est illisible : copie annulée, rien n’a été écrit.`
275
290
  );
276
291
  }
277
- copy[column] = plain;
292
+ copy[column] = t.redact?.[column]?.(plain) ?? plain;
278
293
  } else copy[column] = toWire(value);
279
294
  }
280
295
  out[t.table].push(copy);
@@ -375,7 +390,14 @@ export async function importItemTree(
375
390
  );
376
391
  }
377
392
  values[column] = mapped;
378
- } else if (sealed.has(column) && typeof raw === 'string' && raw !== '') {
393
+ } else if (sealed.has(column) && raw !== null && raw !== '') {
394
+ // Anything but text would land in an encrypted column unsealed.
395
+ if (typeof raw !== 'string') {
396
+ throw new FeatureError(
397
+ 'validation',
398
+ `Valeur inattendue dans la copie : ${t.table}.${column}.`
399
+ );
400
+ }
379
401
  values[column] = await cipher.encrypt(raw);
380
402
  } else values[column] = fromWire(raw);
381
403
  }
@@ -0,0 +1,28 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+
4
+ import { csvCell, toCsv } from './csv';
5
+
6
+ test('csvCell: a formula trigger gets an apostrophe, a number does not, a separator gets quotes', () => {
7
+ assert.equal(csvCell('=SUM(A1:A9)'), "'=SUM(A1:A9)");
8
+ assert.equal(csvCell('@cmd'), "'@cmd");
9
+ assert.equal(csvCell('+33 6 12 34 56 78'), "'+33 6 12 34 56 78");
10
+ assert.equal(csvCell('-12.50'), '-12.50');
11
+ assert.equal(csvCell('-12,50'), '-12,50');
12
+ assert.equal(csvCell('a;b'), '"a;b"');
13
+ assert.equal(csvCell('a,b', ','), '"a,b"');
14
+ assert.equal(csvCell('a,b'), 'a,b');
15
+ assert.equal(csvCell('dit "oui"'), '"dit ""oui"""');
16
+ assert.equal(csvCell('ligne\nsuite'), '"ligne\nsuite"');
17
+ });
18
+
19
+ test('toCsv: a byte order mark, CRLF rows, the separator of choice', () => {
20
+ assert.equal(
21
+ toCsv([
22
+ ['a', 'b'],
23
+ ['1', '=2']
24
+ ]),
25
+ "\ufeffa;b\r\n1;'=2"
26
+ );
27
+ assert.equal(toCsv([['a', 'b']], ','), '\ufeffa,b');
28
+ });
package/src/sdk/csv.ts ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * A CSV a spreadsheet opens as a table and never evaluates. The byte order
3
+ * mark makes Excel read UTF-8 as UTF-8; the separator defaults to the one a
4
+ * French Excel expects.
5
+ */
6
+ export function toCsv(rows: readonly (readonly string[])[], separator = ';'): string {
7
+ return `\ufeff${rows.map((row) => row.map((cell) => csvCell(cell, separator)).join(separator)).join('\r\n')}`;
8
+ }
9
+
10
+ /**
11
+ * One cell. Quoted when it carries the separator, a quote or a line break;
12
+ * prefixed with an apostrophe when it starts with a formula trigger (`=`, `+`,
13
+ * `-`, `@`, a tab, a carriage return) without being a plain number: quoting
14
+ * alone changes nothing, the spreadsheet strips the quotes before it evaluates.
15
+ * Content that came from a form, a bank statement or a database is someone
16
+ * else's text.
17
+ */
18
+ export function csvCell(value: string, separator = ';'): string {
19
+ const formula = /^[=+\-@\t\r]/.test(value) && !/^-?\d+(?:[.,]\d+)?$/.test(value);
20
+ const safe = formula ? `'${value}` : value;
21
+ return safe.includes(separator) || /["\r\n]/.test(safe)
22
+ ? `"${safe.replace(/"/g, '""')}"`
23
+ : safe;
24
+ }
@@ -59,7 +59,10 @@ export interface SavedDeviceChoice {
59
59
  authorUserId?: number | null;
60
60
  }
61
61
 
62
- /** The chosen device, if the caller may open its network; a `validation` error when none is chosen. */
62
+ /**
63
+ * The chosen device, if the caller may open its network and confirmed with an
64
+ * authenticator code lately (`control`); a `validation` error when none is chosen.
65
+ */
63
66
  export async function authorizeRelayDevice(
64
67
  ctx: SdkFeatureContext<unknown>,
65
68
  deviceId: string | null,
@@ -68,7 +71,10 @@ export async function authorizeRelayDevice(
68
71
  if (!deviceId) {
69
72
  throw new FeatureError('validation', `Choisissez l’appareil par lequel joindre ${what}.`);
70
73
  }
71
- return ctx.deveye.devices.authorize(deviceId, { extras: [DEVICE_NETWORK_RIGHT] });
74
+ return ctx.deveye.devices.authorize(deviceId, {
75
+ extras: [DEVICE_NETWORK_RIGHT],
76
+ control: true
77
+ });
72
78
  }
73
79
 
74
80
  /**
package/src/sdk/index.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  * `@deveye/types/sdk/client` (component contracts), `@deveye/types/sdk/testing`
7
7
  * (handler test harness).
8
8
  */
9
+ export * from './csv';
9
10
  export * from './deviceRelayOption';
10
11
  export * from './ids';
11
12
  export * from './manifest';